简体   繁体   English

上传文件的cURL命令不上传文件

[英]cURL command to upload file does not upload file

So I have a Java API and I use cURL commands to send GET/POST requests to my API.所以我有一个 Java API,我使用 cURL 命令向我的 API 发送 GET/POST 请求。 I'm using Springboot in my Java API.我在 Java API 中使用 Springboot。 My cURL command looks like this:我的 cURL 命令如下所示:

curl -X POST \
  https://localhost:8443/abc/code/v \
  -H 'Content-Type: multipart/form-data' \
  -F file=@/path/to/file.txt

and my Java Springboot method that receives this request looks like this:我的 Java Springboot 方法接收这个请求是这样的:

@RequestMapping(method = RequestMethod.POST, value = "/{code}/{v}")
    public ResponseEntity<Object> uploadTemplate( //
            @ApiParam(value = "code desc") //
            @PathVariable final String code, //
            @ApiParam(value = "v desc") //
            @PathVariable final String v, //
            @RequestParam("file") MultipartFile file
    ) throws IOException {
        //log.info("received [url: /tabc/" + code + "/" + v + ", method: POST");
        System.out.println("file: "+ file.getName());
}

which prints out "file: file"打印出"file: file"

It doesn't look like file.txt is uploaded to the server at all!看起来file.txt根本没有上传到服务器! What am I doing wrong?我究竟做错了什么? I've looked up on Google but it looks like I'm doing nearly everything.我在谷歌上查过,但看起来我几乎什么都在做。

The MultipartFile.getName returns the name of the parameter in the multipart form. MultipartFile.getName以多部分形式返回参数的名称。

To get the bytes of the MultipartFile use file.getBytes()要获取MultipartFile的字节,请使用file.getBytes()

And if your MultipartFile is a text file you could use this utility method to retrieve a list of the lines in that text file:如果您的MultipartFile是一个文本文件,您可以使用此实用程序方法来检索该文本文件中的行列表:

    public List<String> read(MultipartFile file) throws IOException {
        InputStreamReader in = new InputStreamReader(file.getInputStream());
        try (BufferedReader reader = new BufferedReader(in)) {
            return reader.lines().collect(Collectors.toList());
        }
    }

Complete code on GitHub GitHub 上的完整代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM