我正在使用spring 4和Apache Tomcat 7开发一个网站,并且我在尝试使用inputFile上传图像时遇到了一些问题。当我检查控制器中的参数时,它们始终为空。 这是我的HTML代码:
<form action="product.htm" method="post"
enctype="multipart/form-data">
<p>Product name:</p>
<p style="text-align: left;"><input type = "text" id="productName" name="productName" required="required" /></p>
<p>Product description:</p>
<p style="text-align: left;"><input type = "text" id="productDescription" name="productDescription" /></p>
<p>Product category</p>
<p style="text-align: left;"><select id="productcategory" name="productcategory">
<c:forEach var="item" items="${categories}" varStatus="loop">
<option value="<c:out value="${item.getIdproductCategory()}"/>"><c:out value="${item.getCategory()}"/></option>
</c:forEach>
</select></p>
<p>Select a file to upload:</p>
<input type="file" name="file" size="50" />
<br />
<p style="text-align: left;"><input type="submit" id="submit" name="submit" value="<spring:message code="label.submit"></spring:message>" /></p>
</form>
这是我的控制器代码:
@Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
ModelAndView mv = new ModelAndView("product");
if (hsr.getParameter("submit") != null) {
insertProduct(hsr);
mv.addObject("send", true);
} else {
mv.addObject("send", false);
}
return mv;
}
public void insertProduct(HttpServletRequest hsr) {
try {
boolean isMultipart;
String filePath;
filePath
= hsr.getServletContext().getInitParameter("file-upload");
int maxFileSize = 50 * 1024;
int maxMemSize = 4 * 1024;
File file;
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("http://localhost:8080/LasDelicias2/resources/images"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(hsr);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
}
}
} catch (Exception ex) {
System.out.println(ex);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
我找到了这个链接:upload servlet
我需要使用参数,因为我在数据库中保存了一些字段。 谢谢你的时间。