Uploading image using SpringMVC 4.0 Multipart

2019-07-19 05:44发布

问题:

I'm trying to upload an image online using the code below. But, the image doesn't seem to be created in the images folder for some reason. Not sure, what Im doing wrong in here.

@RequestMapping(value="/add", method=RequestMethod.POST)
public String processAddNewProductForm(@ModelAttribute("newProduct") Product productToBeAdded, BindingResult result, HttpServletRequest request) {
    String[] supressedFields = result.getSuppressedFields();
    if(supressedFields.length > 0) {
        throw new RuntimeException("Attempting to bind disallowed fields: " + StringUtils.arrayToCommaDelimitedString(supressedFields));
    }

    MultipartFile productImage = productToBeAdded.getProductImage();

    String rootDirectory = request.getSession().getServletContext().getRealPath("/");
    if (productImage!=null && !productImage.isEmpty()) {
      try {
        productImage.transferTo(new File(rootDirectory+"resources\\images\\"+ productToBeAdded.getProductId() + ".png"));
        } catch (Exception e) {
          throw new RuntimeException("Product Image saving failed", e);
        }
    }


    productService.addProduct(productToBeAdded);
    return "redirect:/products/";

}

dispatcherservlet

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10240000" />
</bean>

Product.java

 public class Product {

private String productId;
private String name;
private BigDecimal unitPrice;
private String description;
private String manufacturer;
private String category;
private long unitsInStock;
private long unitsInOrder;
private boolean discontinued;
private String condition;
private MultipartFile productImage;


public Product() {
super();
}

public Product(String productId, String name, BigDecimal unitPrice) {
this.productId = productId;
this.name = name;
this.unitPrice = unitPrice;
}

// add setters and getters for all the fields here

public MultipartFile getProductImage() {
return productImage;
}

public void setProductImage(MultipartFile productImage) {
this.productImage = productImage;
}

public String getProductId() {
return productId;
}

public void setProductId(String productId) {
this.productId = productId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public BigDecimal getUnitPrice() {
return unitPrice;
}

public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getManufacturer() {
return manufacturer;
}

public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

public long getUnitsInStock() {
return unitsInStock;
}

public void setUnitsInStock(long unitsInStock) {
this.unitsInStock = unitsInStock;
}

public long getUnitsInOrder() {
return unitsInOrder;
}

public void setUnitsInOrder(long unitsInOrder) {
this.unitsInOrder = unitsInOrder;
}

public boolean isDiscontinued() {
return discontinued;
}

public void setDiscontinued(boolean discontinued) {
this.discontinued = discontinued;
}

public String getCondition() {
return condition;
}

public void setCondition(String condition) {
this.condition = condition;
}

product.jsp

  <div class="col-md-5"> <img src="<c:url value="/resources/images/${product.productId}.png">           </c:url>" alt="image" style="width: 100%" />

回答1:

There still may be many problems.

First, you named your resolver multipartResolver. Unless you configured specially the MultipartFilter, it looks for it under the name filterMultipartResolver.

Next you configured your resolver in dispatcherservlet. Even if a filter is a web element, it is independant of any servlet and uses the root application context.

Even if you didn't show it, I suppose that you configured a MultipartFilter in the web.xml file.

You seem to simply add a MultipartFile to your Product. According to the javadoc the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storages will be cleared at the end of request processing. You should use something like :

private byte[] image;

public void setProductImage(MultipartFile productImage) {
    image = productImage.getBytes();
}

if you want to store the image in product. Else you should transfer it to a file (File dest = ...; productImage.tranferTo(dest);) and store the name in product.