Working with MultipartFile in Spring 5 MVC returns null


Good morning Community.

I have the typical problem of not being able to upload an image to a directory on the server, I have tried several alternatives but without success. Here I leave part of my code.

Configuration Bean

public CommonsMultipartResolver multipartResolver()
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    return resolver;

Domain Class

private MultipartFile producImage;

public MultipartFile getProductImage() {
    return producImage;

public void setProducImage(MultipartFile producImage) {
    this.producImage = producImage;

Controller Class

@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));

    MultipartFile productImage = newProduct.getProductImage(); // productImage siempre es null!!!!!!!!!!!
    String rootDirectory = request.getSession().getServletContext().getRealPath("/");
    if(productImage != null && !productImage.isEmpty())
            productImage.transferTo(new File(rootDirectory + "resources\images\" + newProduct.getProductId() + ".png"));
        catch(Exception ex)
            throw new RuntimeException("Product Image Saving failed", ex);

    return "redirect:/market/products";

FrontEnd: addproduct.jsp

<form:form method="POST" modelAttribute="newProduct" class="form-horizontal" enctype="multipart/form-data">
                <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" />
                    <div class="col-lg-10">
                        <form:input id="productImage" path="productImage" type="file" class="form:input-large" />
                <div class="form-group">
                    <div class="col-lg-offset-2 col-lg-10">
                        <input type="submit" id="btnAdd" class="btn btn-primary" value ="Add"/>

Up to here the code I use to upload the image but without success yet.

Thanks for your help.

asked by harpazo 01.12.2018 в 22:01

0 answers