【问题标题】:Uploading File from console application to WebAPI将文件从控制台应用程序上传到 WebAPI
【发布时间】:2018-12-05 12:46:32
【问题描述】:

我正在尝试将文件 + 一些信息发布到我控制的 WebApi。我的问题是WebAPI端无法访问文件,其他字段都OK。

这是我的控制台应用程序代码

using (HttpClient client = new HttpClient())
{
    using (MultipartFormDataContent content = new MultipartFormDataContent())
    {
        string filename = "my_filename.png";

        content.Add(new StringContent(DateTime.Now.ToString("yyyy-MM-dd")), "data");


        byte[] file_bytes = webClient.DownloadData($"https://my_url/my_file.png");
        content.Add( new ByteArrayContent(file_bytes), "file");

        string requestUri = "http://localhost:51114/api/File";

        HttpResponseMessage result = client.PostAsync(requestUri, content).Result;
        Console.WriteLine("Upload result {0}", result.StatusCode);
    }
}

这是我的 WebAPI 代码

 [HttpPost]
 public void Post(IFormFile file, [FromForm] DateTime data)
 {
     if (file == null || file.Length == 0)
     {
         Response.StatusCode = StatusCodes.Status400BadRequest;
         return;
     }
     // Never reaches this point..... file is null

 }

关于我可能缺少什么的任何指针?

【问题讨论】:

    标签: c# asp.net-web-api .net-core


    【解决方案1】:

    如果我没记错的话,您可以将文件提交到 WebAPI 端点,将其作为 FormData 和 Content-Type : multipart/form-data 发送,类似这样。

    [HttpPost]
    [Route("..."]
    public void ReceiveFile()
    {
         System.Web.HttpPostedFile file = HttpContext.Current.Request.Files["keyName"];
         System.IO.MemoryStream mem = new System.IO.MemoryStream();
         file.InputStream.CopyTo(mem);
         byte[] data = mem.ToArray();
         // you can replace the MemoryStream with file.saveAs("path") if you want.
    
    }
    

    【讨论】:

    • 谢谢。 +1,但它没有解决我的问题。我认为问题出在发送部分,因为我可以使用很好的方法来解决失眠问题。
    【解决方案2】:

    假设您只发送一个文件(注意),您可以提取内容并将其转换为 2 行代码中的字节数组(注意)使用异步进行文件上传是个好主意,这样您就不会消费为很多CPU时间:

    var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
    var file = provider.Contents.Single();
    

    【讨论】:

    • 谢谢。 +1,但它并没有解决我的问题。我认为问题出在发送部分,因为我可以使用很好的方法来解决失眠问题。
    猜你喜欢
    • 2017-04-19
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    相关资源
    最近更新 更多