将文件从控制台应用程序上传到 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();