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

查看:101
本文介绍了将文件从控制台应用程序上载到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天全站免登陆