将文件从控制台应用程序上传到 WebAPI [英] Uploading File from console application to WebAPI

查看:36
本文介绍了将文件从控制台应用程序上传到 WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to post a file + some info to a WebApi I control. My problem is that I can't access the file on the WebAPI side, all other fields are OK.

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

Here is my Console Application code

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 代码

Here is my WebAPI Code

 [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

 }

关于我可能遗漏的任何指示?

Any pointers on what I might be missing?

推荐答案

2行代码就可以把内容抓出来转成字节数组,假设你只发送一个文件(注)就好了使用异步进行文件上传的想法,这样您就不会消耗尽可能多的 CPU 时间:

You can grab out the content and convert it into a byte array in 2 lines of code, assuming you are only sending a single file (Note) its a good idea to use async for file upload so you don't consume as much cpu time:

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

这篇关于将文件从控制台应用程序上传到 WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆