【问题标题】:How to send multipartFile and Json with postman and spring boot如何使用邮递员和 Spring Boot 发送 multipartFile 和 Json
【发布时间】:2017-11-14 20:05:59
【问题描述】:

我想在一个发布请求中发送一个文件和一个 json 模型。

我的请求映射如下所示:

@ResponseBody
@RequestMapping(value = "/sftp/upload", method = RequestMethod.POST)
public ResponseEntity<SftpModel> upload(@RequestPart("file") MultipartFile file, @RequestPart("sftpModel") SftpModel sftpModel) {

我的 Json 有这样的结构:

{
  "sftpHost": "ftp01.Host.de",
  "sftpPort": 22,
  "sftpUser": "anyUser",
  "sftpPassword": "anyPass",
  "sftpRemoteDirectory": "/"
}

该文件在我的系统上。

我可以单独发送filesftpModel,但不能同时发送。我收到的错误是:

{
  "timestamp": 1497336812907,
  "status": 415,
  "error": "Unsupported Media Type",
  "exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
  "message": "Content type 'application/octet-stream' not supported",
  "path": "/secure-data-transfer-service/sftp/upload"
}

我用 postman 和 curl 试过了。但没有机会。

curl --form "file=@test.txt" --form "sftpModel={"sftpHost":"ftp01.Host.de","sftpPort":22,"sftpUser":"anyUser","sftpPassword":"anyPass","sftpRemoteDirectory":"/"}" http://localhost:8080/secure-data-transfer-service/sftp/upload

有什么方法可以同时发送吗?

【问题讨论】:

  • 您能否更具体地说明什么不起作用?您是否收到任何具体错误或任何其他可以与我们分享的信息?
  • @ValentinDespa 这不是我想做的。我只想通过一个请求发布一个文件和一个 json 模型。我得到的错误在我的问题中。如果我创建一个 sftpModel.json 文件而不是编写模型本身,它可以工作
  • 这东西在我身边运行良好。
  • @Patrick 你能找到解决方案吗?我遇到了同样的问题。
  • @NewQueries 没有。我刚刚通过 multipart 发送文件并将 json 作为请求参数来让它工作。

标签: json spring spring-boot postman


【解决方案1】:

你的java代码看起来很完美。

@ResponseBody @RequestMapping(value = "/sftp/upload", method = RequestMethod.POST) public ResponseEntity<SftpModel> upload(@RequestPart("file") MultipartFile file, @RequestPart("sftpModel") SftpModel sftpModel) { }

您可以将您的 SftpModel json 字符串写入一个 json 文件并尝试使用该 json 文件上传。

Click here to see the postman image

【讨论】:

    【解决方案2】:

    请尝试以下代码:

    public ResponseEntity<?> uploadFile(@RequestPart MultipartFile file, @RequestPart String user) {
                User users = new ObjectMapper().readValue(user, User.class);
    }
    

    【讨论】:

    • 请使用正确的格式以使您的答案更具可读性
    • 问题中的代码和我什至没有用户类有什么区别......
    猜你喜欢
    • 1970-01-01
    • 2022-12-29
    • 2019-08-03
    • 2019-04-17
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多