【问题标题】:How to send the Multipart file and json data to spring boot如何将Multipart文件和json数据发送到spring boot
【发布时间】:2019-03-19 23:05:54
【问题描述】:

我有 POST 请求 api 调用来接受来自客户端(邮递员或 java 客户端)的 json 正文请求参数和多部分文件。

我想在单个请求中同时传递 json 数据和多部分文件。

我已经编写了如下代码。

@RequestMapping(value = "/sendData", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<MailResponse> sendMail(@RequestPart MailRequestWrapper request) throws IOException

但是,我无法使用邮递员休息客户端完成它。

我在服务器端使用 spring boot。

有人可以就这个问题给我建议吗?

提前致谢,

【问题讨论】:

标签: json rest spring-boot postman


【解决方案1】:

你猫使用 @RequestParamConverter 作为 JSON 对象
简单的例子:

@SpringBootApplication
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Data
    public static class User {
        private String name;
        private String lastName;
    }

    @Component
    public static class StringToUserConverter implements Converter<String, User> {

        @Autowired
        private ObjectMapper objectMapper;

        @Override
        @SneakyThrows
        public User convert(String source) {
            return objectMapper.readValue(source, User.class);
        }
    }

    @RestController
    public static class MyController {

        @PostMapping("/upload")
        public String upload(@RequestParam("file") MultipartFile file, 
                             @RequestParam("user") User user) {
            return user + "\n" + file.getOriginalFilename() + "\n" + file.getSize();
        }

    }

}

和邮递员:

更新 apachehttpclient 4.5.6 示例:

pom.xml 依赖:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.6</version>
    </dependency>

   <!--dependency for IO utils-->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>

服务将在应用程序完全启动后运行,更改您的文件的File路径

@Service
public class ApacheHttpClientExample implements ApplicationRunner {

    private final ObjectMapper mapper;

    public ApacheHttpClientExample(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void run(ApplicationArguments args) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            File file = new File("yourFilePath/src/main/resources/foo.json");
            HttpPost httpPost = new HttpPost("http://localhost:8080/upload");

            ExampleApplication.User user = new ExampleApplication.User();
            user.setName("foo");
            user.setLastName("bar");
            StringBody userBody = new StringBody(mapper.writeValueAsString(user), MULTIPART_FORM_DATA);
            FileBody fileBody = new FileBody(file, DEFAULT_BINARY);

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addPart("user", userBody);
            entityBuilder.addPart("file", fileBody);
            HttpEntity entity = entityBuilder.build();
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();

            // print response
            System.out.println(IOUtils.toString(responseEntity.getContent(), UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

控制台输出如下所示:

ExampleApplication.User(name=foo, lastName=bar)
foo.json
41

【讨论】:

  • 所以,使用转换器后。我可以通过邮递员休息客户端将多部分文件和表单数据接收到spring boot api中。感谢您的时间和帮助。你有什么想法使用 java application apache http
  • 不客气,我更新了答案并添加了一个 apache HttpClient 示例
  • 在请求参数中发送 json 不是一个好主意和实现。我投反对票。
【解决方案2】:

你有两个选择-

随 json 数据发送 MultipartFile

public void uploadFile(@RequestParam("identifier") String identifier, @RequestParam("file") MultipartFile file){
}

在 MultipartFile 中发送 Json 数据,然后解析 Multipart 文件,如下所述。

public void uploadFile(@RequestParam("file") MultipartFile file){
    POJO p = new ObjectMapper().readValue(file.getBytes(), POJO.class);
}

【讨论】:

    【解决方案3】:

    过去几个小时我一直被这个问题困扰

    所以我遇到了this 的问题。

    总结:
    使用@ModelAttribute 而不是@RequestBody@ModelAttriute 将像其他正常(实体中没有多部分属性)实体映射一样工作。

    【讨论】:

      【解决方案4】:

      我在回答部分中解释了所有内容:

      enter link description here

      【讨论】:

        【解决方案5】:

        你可以同时使用它们。

        @RequestPart :此注解将多部分请求的一部分与方法参数相关联,这对于将复杂的多属性数据作为有效负载(例如 JSON 或 XML)发送非常有用。

        换句话说,请求部分将您的 json 字符串对象从请求解析为您的类对象。另一方面,Request Param 只是从您的 json 字符串值中获取字符串值。

        例如,使用请求部分:

        @RestController
        @CrossOrigin(origins = "*", methods= {RequestMethod.POST, RequestMethod.GET,
        RequestMethod.PUT})
        @RequestMapping("/api/api-example")
        public class ExampleController{    
        @PostMapping("/endpoint-example")
        public ResponseEntity<Object> methodExample(
            @RequestPart("test_file") MultipartFile file,
            @RequestPart("test_json") ClassExample class_example) { 
              /* do something */ 
         }
        }
        

        邮递员的配置如下:

        @RequestParam:另一种发送多部分数据的方法是使用@RequestParam。这对于简单的数据特别有用,作为键/值对与文件一起发送,正如我所说,只是键/值。也用于从查询参数中获取价值,我认为这是它的主要目标。

        【讨论】:

          猜你喜欢
          • 2015-09-24
          • 2016-10-25
          • 2018-09-25
          • 1970-01-01
          • 2020-08-04
          • 1970-01-01
          • 2016-10-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多