I am using Jsps/Servlets to allow users to upload images (as outlined here: How to upload files to server using JSP/Servlet?)
Ordinarily everything works ok (I have the MultipartConfig
annotation on the appropriate servlet).
I got one case where a NullPointerException
was thrown when trying to retrieve the part from the HttpServletRequest
: request.getPart()
.
According to the docs, this happens when the request
doesn't contain the "requested part" (http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getPart(java.lang.String)).
So, the only way I could recreate this issue was manipulating the html (via my browser's html editing tool) and manually erasing the name
attribute of the file input
element (ie: changing the name
to an empty string).
I find it very unlikely that this is what the user did to cause the exception to be thrown. Are there any other reasons that this error might have occurred? I'd like to figure out what the cause was.
Thank you.
UPDATE
Relevant html: (uses bootstrap collapse to display file input
element)
(The data attributes are for javascript - maybe something with the quotations is messing with the name
attribute?)
<form role="form" action="/fileUploadServlet" method="post"
enctype="multipart/form-data"
data-min-length='${minLength}'
data-max-length='${maxLength}'
data-msg="${valMsg}"
data-size="${maxSize}">
<a href="#input_collapse" class="btn btn-default" data-toggle="collapse">
Upload File
</a>
<span class="collapse" id="input_collapse">
<input type="file" name="someFile" id="some_file">
</span>
...[other form fields]
</form>
Relevant Servlet code: (calling getSubmittedFileName()
throws the NPE
)
@MultipartConfig(maxFileSize = 1024*1024*5)
public class FileUploadServlet
{
...
try {
Part filePart = req.getPart("someFile");
...filePart.getSubmittedFileName();