我如何在自托管web API上发送文件并在服务器上处理它

本文关键字:文件 服务器 处理 API web | 更新日期: 2023-09-27 18:07:36

我有一个使用Owin和Katana的自托管web api。我想从一个示例客户机发送文件(可能非常大,几百MB),并希望将这些文件保存在服务器的磁盘上。目前正在我的本地机器上测试服务器。

我在测试客户端的机器上有以下内容(这里是image,但并不总是image):

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的servicecontroller的Post方法中收到的文件。我看到了其他一些使用HttpContext的例子。当前的,但由于它是自托管的,它似乎是空的。

我如何在自托管web API上发送文件并在服务器上处理它

我会在上传之前将文件分割成块。对于单个HTTP POST请求来说,100 Mb有点大。大多数web服务器对HTTP请求大小也有一定的限制。

如果连接超时,您将不需要重新发送所有数据。

不管你是使用self hosting还是IIS,也不管它是一个图像文件还是任何类型的文件。

你可以检查我的答案,它会给你简单的代码来完成

https://stackoverflow.com/a/10765972/71924

关于大小,如果可能的话,块肯定更好,但这会给您的客户端(除非您也拥有API客户端代码)和服务器上的您带来更多的工作,因为您必须重新构建文件。

这将取决于是否所有文件将超过100MB或如果只有少数。如果它们一直很大,我建议寻找http字节范围支持。这是http标准的一部分我相信你能找到使用WebAPI实现它的人