Why does Servlet think my empty HTML file element has a file in it? -
i using java servlet handle html form , includes file input element:
<input type="file" id="fileupload" name="file" multiple />
i used example code in this excellent answer process multiple files @ once. code i'm using is:
list<part> fileparts = req.getparts().stream().filter(part -> "file".equals(part.getname())).collect(collectors.tolist()); // retrieves <input type="file" name="file" multiple="true"> (part filepart : fileparts) { string filename = filepart.getsubmittedfilename(); inputstream filecontent = filepart.getinputstream(); // stuff here }
this code works great. problem is, when don't attach anything, code still thinks fileparts has part object in it. doing debugging, part object seem there, of course there no inputstream or submittedfilename get, since didn't upload files. why this? new lambda functions , collections, seems "fileparts" collection should empty when don't select files upload.
this how html works.
the same true non-file inputs. when empty input submitted, empty value, not null
. difference significant. value of null
represents absence of input field. particularly useful when form has multiple submit buttons , you'd distinguish button pressed.
given <input type="text" name="foo">
,
string foo = request.getparameter("foo"); if (foo == null) { // foo not submitted @ all. } else if (foo.isempty()) { // foo submitted without value. } else { // foo submitted value. }
and <input type="file" name="bar">
,
part bar = request.getpart("bar"); if (bar == null) { // bar not submitted @ all. } else if (bar.getsize() == 0) { // bar submitted without value. } else { // bar submitted value. }
Comments
Post a Comment