简体   繁体   English

如何在Spring MVC中使用multipart / form-data

[英]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. 当我按下此api时,出现错误“ 415:不支持的媒体类型”,这表示不支持标题。我想将文件从ARC加载到控制器。

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; Java类org.springframework.web.multipart.MultipartFile和Java类型接口org.springframework.web.multipart.MultipartFile和MIME媒体类型multipart / form-data的消息正文阅读器; boundary=----WebKitFormBoundaryP1d7Atv9FO9wU301 was not found. boundary = ----未找到WebKitFormBoundaryP1d7Atv9FO9wU301。 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 与MIME媒体类型兼容的已注册邮件正文阅读器为: / -> 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. 我在pom.xml文件中添加了一些Maven依赖项。

My pom file: 我的pom文件:

<!-- 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 我不确定您编写的代码,但是这是我在spring-mvc中做到的

Use case: uploading Images 用例:上传图片

  1. Add a bean definition in our web application's context configuration file (DispatcherServlet-context.xml) for CommonsMultipartResolver, 在我们的Web应用程序的上下文配置文件(DispatcherServlet-context.xml)中为CommonsMultipartResolver添加一个bean定义,
    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; 将依赖项添加到pom.xml中,将“组ID”输入commons-fileupload,将“ Artifact ID”输入commons-fileupload,将Version输入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; 同样,再添加一个Group Id依赖项作为org.apache.commons,将Artifact Id添加为commons-io,将版本添加为1.3.2; select Scope as compile; 选择范围作为编译; click on the OK button; 单击确定按钮; and save the pom.xml file 并保存pom.xml文件

  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: org.springframework.web.multipart.MultipartFile与java类中的相应setter和getter一起,将文件定义为属性,如下所示:

     @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 在要上传文件的jsp中,使用以下标记

  6. Set the enctype attribute to multipart/form-data in the form tag as follows in the jsp 在jsp中,如下所示,在表单标签中将enctype属性设置为multipart / form-data。

Note: I am using spring form tag libraries 注意:我正在使用spring表单标签库

<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 少数注释和代码行特定于我的项目,可能并不完全相关

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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