如何将Multipart文件和json数据发送到Spring Boot

时间:2018-10-15 13:40:16

标签: json rest spring-boot postman

我有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。

有人可以在这个问题上建议我吗。

预先感谢

4 个答案:

答案 0 :(得分:4)

您可以将@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();
        }

    }

}

和邮递员: enter image description here

更新 apache httpclient 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

答案 1 :(得分:1)

我在回答部分解释了一切:

enter link description here

答案 2 :(得分:0)

您有两个选择-

与JSON数据一起发送MultipartFile

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

}

OR

在MultipartFile中发送Json数据,然后按以下所述解析Multipart文件,就这样。

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

}

答案 3 :(得分:0)

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

所以我遇到了this个问题。

摘要:
使用@ModelAttribute代替@RequestBody@ModelAttriute的工作原理与其他普通(实体中没有multipart属性的)实体映射一样。