我有一个使用 Owin 和 Katana 的自托管网络 API。我想从示例客户端发送文件(可能很大,几百 MB),并想将这些文件保存在服务器的磁盘上。目前只是在我的本地机器上测试服务器。
我在测试客户端的机器上有以下内容(这里说的是图像,但并不总是图像):
using System;
using System.IO;
using System.Net.Http;
class Program
{
string port = "1234";
string fileName = "whatever file I choose will be here";
static void Main(string[] args)
{
string baseAddress = "http://localhost:" + port;
InitiateClient(baseAddress);
}
static void InitiateClient(string serverBase)
{
Uri serverUri = new Uri(serverBase);
using(HttpClient client = new HttpClient())
{
client.BaseAddress = serverUri;
HttpResponseMessage response = SendImage(client, fileName);
Console.WriteLine(response);
Console.ReadLine();
}
}
private static HttpResponseMessage SendImage(HttpClient client, string imageName)
{
using (var content = new MultipartFormDataContent())
{
byte[] imageBytes = System.IO.File.ReadAllBytes(imageName);
content.Add(new StreamContent(new MemoryStream(imageBytes)), "File", "samplepic.png");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data"));
return client.PostAsync("api/ServiceA", content).Result;
}
}
首先,这是使用 POST 发送文件的正确方法吗?
现在我真的迷路了。我不确定如何保存我在继承 ApiController 的 ServiceAController 的 Post 方法中收到的文件。我看到了其他一些使用 HttpContext.Current 的示例,但由于它是自托管的,因此它似乎为空。
最佳答案
我会在上传前将文件拆分成 block 。 100 Mb 对于单个 HTTP POST 请求来说有点大。大多数网络服务器也对 HTTP 请求大小有一定的限制。
通过使用 block ,如果连接超时,您将不需要再次重新发送所有数据。
关于c# - 如何在自托管 Web API 上发送文件并在服务器上处理它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954159/