Reputation: 641
I need to upload a file by HTML but my form request has to include other parameters and values, for this i made the following:
I have the following html form:
<form action="CustomerAccountingServlet" method="post" name="payment_list_form" enctype="multipart/form-data">
<input type="hidden" name="action" value="save_payment" />
<input type="hidden" name="customer_id" value="123"/>
<input type="hidden" name="payment_id" value="444" />
<input type="file" name="invoice_file" />
<input type="submit" value="upload" />
</form
I use the following java code to get the file:
public static InputStream uploadFile(HttpServletRequest request, String fileFieldName) {
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = request.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File(filePath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
upload.setHeaderEncoding("utf-8");
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
if(fi.getFieldName().equals(fileFieldName)){
return fi.getInputStream();
}
}
}
} catch (Exception ex) {
System.out.println(ex);
}
} else {
System.out.println("No file was found");
}
return null;
}
The problem that i get null when i do in the servlet the following:
request.getParameter("action");
request.getParameter("customer_id");
request.getParameter("payment_id");
Anyone can help please? Thanks!
Upvotes: 0
Views: 1433
Reputation: 1194
You cannot reference request parameters for multipart/form-data request in the conventional way. All the parameters are encoded in the multipart data, along with the uploaded file. See for example this blog post for an extended example of how this should be handled.
Upvotes: 1