Intellij IDEA REST客户端文件上传

8

我正在尝试通过Intellij IDEA REST客户端上传文件。我选择“要上传的文件(multipart/form-data)”,并选择要发送的文件。这个文件的参数名称是什么?在我的Sprint控制器中,我使用以下代码:

@RequestMapping(method = RequestMethod.POST, value = "/{id}/photo")
public void setCover(@PathVariable int id,
                     @RequestParam MultipartFile file) {
    System.out.println(file.getName());
}

我还尝试了不同的名称,例如“file”,“fileToSend”,“File to send”作为@RequestParam的参数,但Spring始终找不到MultipartFile参数。

你能添加你的错误日志吗? - Rana_S
你找到解决方案了吗? - nyxz
@nyxz 不,我刚刚找到了另一个 REST 客户端(适用于 Google Chrome),在其中我可以设置多部分文件的参数名称。我仍然不知道如何在 Intellij Rest Client 中设置它。 - hluhovskyi
我有同样的问题。 - Juru
遇到了同样的问题。使用调试器,看起来名称实际上是文件名本身。由于控制器事先无法知道这一点,因此无法处理。 - gregturn
3个回答

20

我使用以下代码,它对我有效:

POST http://localhost:9003/goods/add HTTP/1.1
Content-Type: multipart/form-data; boundary=boundary

--boundary
Content-Disposition: form-data; name="file"; filename="file.csv"

// The 'input.txt' file will be uploaded
< /Users/xing/Desktop/file.csv
--boundary
Content-Disposition: form-data; name="advertType"

1
--boundary

// The method in the Spring controller
public Xxxx add(@RequestParam("file") MultipartFile file, Long advertType) {

欲了解更多信息,请参阅https://www.jetbrains.com/help/ruby/exploring-http-syntax.html#use-multipart-form-data


我也试了一遍,REST客户端返回了400状态码。 - logbasex
这个解决方案对我有用,但我无法在此处放置代码,因此添加了一个新的回复来支持这个答案。 - A P
你好,直到我在结尾添加了 --boundary-- 才使它对我起作用,无论如何,非常感谢您的时间。 - arrmani88

7

出于安全考虑,不允许进行文件上传,但这并不适用于在本地机器上运行的应用程序。这个解决方案对我有效。它基于 Vincent 的评论。

请见下文:

POST http://localhost:8080/api/test HTTP/1.1
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="param1"; filename="myfile.csv"
Content-Type: application/csv

 // below will the path to the file (i.e. myfile.csv)
< C:/users/user/data/sample/myfile.csv
--WebAppBoundary
Content-Disposition: form-data; name="param2"

 // value of param2
test
--WebAppBoundary

###

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接