我无法将图像上传到服务器中的特定目录。 multipartfile变量始终为空,这是我的代码
配置Bean
@Bean
public CommonsMultipartResolver multipartResolver()
{
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
域类
private MultipartFile producImage;
public MultipartFile getProductImage() {
return producImage;
}
public void setProducImage(MultipartFile producImage) {
this.producImage = producImage;
}
控制器类
@RequestMapping(value = "/products/add", method = RequestMethod.POST)
public String processAddNewProductForm(@ModelAttribute("newProduct") Product newProduct, BindingResult result, HttpServletRequest request)
{
String[] suppressedFields = result.getSuppressedFields();
if(suppressedFields.length > 0)
{
throw new RuntimeException("Attempting to bind disallowed fields " + StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
// productImage always receive null value !!!!!!
MultipartFile productImage = newProduct.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
if(productImage != null && !productImage.isEmpty())
{
try
{
productImage.transferTo(new File(rootDirectory + "resources\\images\\" + newProduct.getProductId() + ".png"));
}
catch(Exception ex)
{
throw new RuntimeException("Product Image Saving failed", ex);
}
}
productService.addProduct(newProduct);
return "redirect:/market/products";
}
FrontEnd:addproduct.jsp
<form:form method="POST" modelAttribute="newProduct" class="form-horizontal" enctype="multipart/form-data">
<fieldset>
<legend>Add New Product</legend>
<div class="form-group">
<label class="control-label col-lg-2" for="productImage">
<spring:message code="addProduct.form.productImage.label" />
</label>
<div class="col-lg-10">
<form:input id="productImage" path="productImage" type="file" class="form:input-large" />
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" id="btnAdd" class="btn btn-primary" value ="Add"/>
</div>
</div>
</fieldset>
</form:form>
我不知道为什么不起作用。感谢您的提前帮助
答案 0 :(得分:0)
您必须初始化一个类型为MultipartFilter的bean并设置多部分解析器,从而使Spring能够处理包含文件的请求:
@Bean
public MultipartFilter multipartFilter(){
MultipartFilter multipartFilter = new MultipartFilter();
multipartFilter.setMultipartResolverBeanName("multipartResolver");
return multipartFilter;
}