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
Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.
String textboxValue = request. getParameter( "textBox1" ); But I always get null value by using this method.
enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server. multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server. Note: The enctype attribute can be used only if method="post" .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With