This question already has an answer here:
I need to upload an image:
<form method="post" action="hi.iq/register.jsp" enctype="multipart/form-data">
Name: <input type="text" name="name" value="J.Doe">
file: <input type="file" name="file-upload">
<input type="submit">
</form>
In my servlet I gave
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
System.out.println("user_id========= "+name);
but the value of name is returned as NULL.
Pls Help
Try <input type="text" id="name" name="name" value="J.Doe">.
Edit:
A sample using Apache Commons Fileupload, as suggested by David's answer:
FileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
// factory.setSizeThreshold(yourMaxMemorySize);
// factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload( factory );
// upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List<FileItem> uploadItems = upload.parseRequest( request );
for( FileItem uploadItem : uploadItems )
{
if( uploadItem.isFormField() )
{
String fieldName = uploadItem.getFieldName();
String value = uploadItem.getString();
}
}
Try
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator<FileItem> iterator = upload.parseRequest(request).iterator();
File uploadedFile;
String dirPath="D:\fileuploads";
while (iterator.hasNext()) {
FileItem item = iterator.next();
if (!item.isFormField()) {
String fileNameWithExt = item.getName();
File filePath = new File(dirPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
uploadedFile = new File(dirPath + "/" + fileNameWithExt);
item.write(uploadedFile);
}
else {
String otherFieldName = item.getFieldName();
String otherFieldValue = item.getString()
}
}
It needs Apache commons-fileupload.jar and commons-io.jar
No container that I have used supports multipart encoded requests out of the box. Due to this, it cannot parse parameters and you cannot use request.getParameter() out of the box.
You need to use something on the server side like Apache Commons FileUpload to preprocess the request
The null value returned by the request.getParameter("name"); is due to the fact that you are using enctype="multipart/form-data" in your html form.
This has been thoroughly answered in this post.
Add Annotaion @javax.servlet.annotation.MultipartConfig and then just simply use request.getParameter() it will work Perfectly.
Or If you are using MultipartFormDataRequest then use its object Like MultipartFormDataRequest mrequest; in place of request for ex. mrequest.getParameter("name"); It works.
来源:https://stackoverflow.com/questions/5512442/input-type-text-value-from-jsp-form-enctype-multipart-form-data-returns-null