简体   繁体   中英

how to use multipart/form-data in spring mvc

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA) 
@Path("/uploadFile")
public POSResponse singleSave(@FormDataParam("file") MultipartFile file) {
        Response response = new Response();
        String fileName = null;
        if (!file.isEmpty()) {
            try {
                fileName = file.getOriginalFilename();
                byte[] bytes = file.getBytes();
                BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(new File("d:\\" + fileName)));
                buffStream.write(bytes);
                buffStream.close();
            } catch (Exception e) {
            }
        } else {

        }
        return response;
}

when i hit this api then i got the error "415: Unsupported Media Type" this means not supported header.I want to load file from ARC to controller.

and my console:

A message body reader for Java class org.springframework.web.multipart.MultipartFile, and Java type interface org.springframework.web.multipart.MultipartFile, and MIME media type multipart/form-data; boundary=----WebKitFormBoundaryP1d7Atv9FO9wU301 was not found. The registered message body readers compatible with the MIME media type are: / -> com.sun.jersey.core.impl.provider.entity.FormProvider com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider com.sun.jersey.core.impl.provider.entity.StringProvider com.sun.jersey.core.impl.provider.entity.ByteArrayProvider com.sun.jersey.core.impl.provider.entity.FileProvider com.sun.jersey.core.impl.provider.entity.InputStreamProvider com.sun.jersey.core.impl.provider.entity.DataSourceProvider

i have add some maven dependency in pom.xml file.

My pom file:

<!-- multipart file dependency -->

    <dependency>
        <groupId>org.jvnet</groupId>
        <artifactId>mimepull</artifactId>
        <version>1.6</version>
    </dependency>

    <dependency>
        <groupId>org.jvnet.mimepull</groupId>
        <artifactId>mimepull</artifactId>
        <version>1.9.5</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.17.1</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-multipart</artifactId>
        <version>1.17.1</version>
    </dependency>

I am not sure about the code which you have written but this how i did it in spring-mvc

Use case: uploading Images

  1. Add a bean definition in our web application's context configuration file (DispatcherServlet-context.xml) for CommonsMultipartResolver,
    as follows:

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

  2. Add dependency to pom.xml enter Group Id as commons-fileupload, Artifact Id as commons-fileupload, Version as 1.2.2; select Scope as compile; and click on the OK button.

  3. Similarly, add one more Group Id dependency as org.apache.commons, Artifact Id as commons-io, Version as 1.3.2; select Scope as compile; click on the OK button; and save the pom.xml file

  4. Add a reference to
    org.springframework.web.multipart.MultipartFile with the corresponding setters and getters in the java class the defines the file as a property as follows:

     @JsonIgnore private MultipartFile productImage; @XmlTransient public MultipartFile getProductImage() { return productImage; } public void setProductImage(MultipartFile productImage) { this.productImage = productImage; } 
  5. In the jsp where the file is to be uploaded use the following tag

  6. Set the enctype attribute to multipart/form-data in the form tag as follows in the jsp

Note: I am using spring form tag libraries

<form:form  modelAttribute="newProduct" class="form-horizontal" enctype="multipart/form-data">
  1. Add the following code to the controller

      public String processAddNewProductForm(@ModelAttribute("newProduct") @Valid Product productToBeAdded, BindingResult result, HttpServletRequest request) { if(result.hasErrors()) { return "addProduct"; } 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"; } 

****Prerequisites****

spring project has been setup correctly, wiring is done

few annotations and lines of code are specific to my project and may not be totally relevant

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM