ASP.NET MVC将大文件上传到REST API

时间:2018-06-22 15:53:16

标签: asp.net-mvc file-upload httpclient

我有一个ASP.Net MVC应用程序,该应用程序通过REST API将文件上传到存储节点。除了使用API​​上传和下载外,我无法控制存储。这是我通常在上传文件上执行的操作。

    [HttpPost]
    public async Task UploadFile()
    {
        //Get stream from file to upload
        using (Stream fileStream = System.IO.File.OpenRead(Request.Files[0].FileName))
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://api-upload.abc.com");
            client.DefaultRequestHeaders.TransferEncodingChunked = true;

            var res = await client.PutAsync("/streaming/" + Path.GetFileName(Request.Files[0].FileName),
                new StreamContent(fileStream));

            ViewBag.Result = res.Result.ToString();
        }
    }

这适用于较小的文件。我想上传大于2GB的文件,在这种情况下,我打算将此应用拆分为大块文件。

            byte[] buffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                //tempStream.Write(buffer, 0, bytesRead);

            }

再次使用这种方法,我需要有一个临时流来合并,因为我需要将文件推送到REST API。这也会遇到内存不足(或磁盘上没有足够的空间)错误。我已经在几篇文章中对此进行了一些阅读,由于服务器端代码中的块合并,jquery控件的某些方法也导致了相同的OOM。我正在寻找.NET解决方案以将文件直接流式传输到Web应用程序中的REST API(如果有)。

我将maxRequestLength和maxAllowedContentLength设置为最大值。

<httpRuntime targetFramework="4.6.1" maxRequestLength="2097152"/>

<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="2147483648"/>
  </requestFiltering>
</security>

以下是上传大文件时的响应。

            HTTP / 1.1 500 Internal Server Error
            Cache - Control: private
            Content-Length: 9918
            Content-Type: text/html; charset=utf-8
            Server: Microsoft-IIS/8.5
            X-AspNet-Version: 4.0.30319
            X-Powered-By: ASP.NET

0 个答案:

没有答案