【问题标题】:upload file with --upload-file to server使用 --upload-file 将文件上传到服务器
【发布时间】:2018-07-17 14:57:46
【问题描述】:

我目前正在尝试创建一个 rest 端点以使用 curl 上传文件。

为此,我想使用名为 --upload-file 的出色内置参数,它将文件上传到服务器。

This has the following properties:

  • 发送 PUT
  • 网址路径是文件名

例如curl --upload-file "texts/test.txt" http://localhost/

它向http://localhost/file.txt发送PUT请求

我现在如何在控制器中定义一个动作来捕获所有的 put 请求?

我试过了:

public class HomeController : Controller {
    [HttpPut]
    [ActionName("Index")]
    public string UploadFilePut() {
    }
}

public class HomeController : Controller {
    [HttpPut]
    [ActionName("Index")]
    public string UploadFilePut(IFormFile file) {
    }
}

但它们都不起作用。

编辑:

curl localhost:57623 --upload-file diamond.sh -v
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  
Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--         0*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 57623 (#0)
> PUT /diamond.sh HTTP/1.1
> Host: localhost:57623
> User-Agent: curl/7.60.0
> Accept: */*
> Content-Length: 1987
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
} [1987 bytes data]
* We are completely uploaded and fine
< HTTP/1.1 404 Not Found
< Date: Tue, 17 Jul 2018 17:47:09 GMT
< Server: Kestrel
< Content-Length: 0
<
100  1987    0     0  100  1987      0  64096 --:--:-- --:--:-- --:--:--     64096
* Connection #0 to host localhost left intact

在服务器上:

      Request starting HTTP/1.1 PUT http://localhost:57623/diamond.sh  1987
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 13.7902ms 404 

【问题讨论】:

  • 当您说它不起作用时,您会得到 404 吗?使用Fiddler Content-Type 标头是否显示为 multipart/form-data?
  • 是的,我收到了 404。我用示例编辑了帖子。
  • 来自manpage 它说“如果指定的 URL 中没有文件部分,curl 将附加本地文件名”。所以你需要把你的命令改成curl --upload-file "texts/test.txt" http://localhost/index
  • 我该怎么做呢?我知道我可以指定正确的路径,但如果我不想包含它怎么办。需要有一个选项/方法。
  • 你需要使用Routing,比如[HttpPut("{filename}.{ext?}")]

标签: rest file-upload asp.net-core put


【解决方案1】:

感谢 Mark G,这是正确的做法:

[HttpPut("{filename}.{ext?}")]
[ActionName("Index")]
public void UploadPut(string filename, string ext) {
    var tmp = new FileInfo("temp");

    Console.WriteLine($"Writing {filename}.{ext} to {tmp.FullName}");
    using (var fs = tmp.OpenWrite()) {
        Request.Body.CopyTo(fs);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2021-11-05
    • 1970-01-01
    • 2021-04-22
    • 2020-12-08
    相关资源
    最近更新 更多