如何将 Multipart 文件和 json 数据发送到 Spring Boot [英] How to send the Multipart file and json data to spring boot

查看:645
本文介绍了如何将 Multipart 文件和 json 数据发送到 Spring Boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我已经编写了如下代码.

@RequestMapping(value = "/sendData", method = RequestMethod.POST,consumes = "multipart/form-data")公共响应实体sendMail(@RequestPart MailRequestWrapper 请求) 抛出 IOException

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

我在服务器端使用 spring boot.

谁能就这个问题向我提出建议.

提前致谢,

解决方案

你的猫使用

更新apache httpclient 4.5.6 示例:

pom.xml 依赖:

 <依赖><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version></依赖><依赖><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.6</version></依赖><!--IO 工具的依赖--><依赖><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></依赖>

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

@Service公共类 ApacheHttpClientExample 实现 ApplicationRunner {私有最终 ObjectMapper 映射器;公共 ApacheHttpClientExample(ObjectMapper 映射器){this.mapper = 映射器;}@覆盖公共无效运行(ApplicationArguments args){尝试 (CloseableHttpClient 客户端 = 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(实体);HttpResponse 响应 = client.execute(httpPost);HttpEntity responseEntity = response.getEntity();//打印响应System.out.println(IOUtils.toString(responseEntity.getContent(), UTF_8));} 捕获(异常 e){e.printStackTrace();}}}

控制台输出如下所示:

ExampleApplication.User(name=foo, lastName=bar)foo.json41

I have the POST request api call to accept the json body request parameters and multipart file from client side(postman or java client).

I want to pass both the json data and multipart file in single request.

I have written the code like below.

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

But, i could not accomplish it using postman rest client.

I'm using spring boot on server side.

Could anyone suggest me on this question.

Thanks in advance,

解决方案

You cat use @RequestParam and Converter for JSON objects
simple example :

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

    }

}

and postman:

UPDATE apache httpclient 4.5.6 example:

pom.xml dependency:

    <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>

service will be run after application fully startup, change File path for your 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();
        }
    }

}

console output will look like below:

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

这篇关于如何将 Multipart 文件和 json 数据发送到 Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆