如何在ASP.Net WebAPI中接收大文件(> 2GB)而没有多部分MIME类型?

时间:2018-06-28 01:38:41

标签: c# asp.net-web-api webapi2

有没有一种方法可以实现.net Web api,以使用没有multipart / form-data mime类型的无缓冲输入流来接收lrage文件(> 2gb)?

我正在尝试使用下面的代码来实现它,但是它没有完全读取流。我正在尝试上传100 MB的文件,但它仅将10MB写入“ c:\ sampl.zip”,然后出来。下面的代码出了什么问题?

        public async Task<HttpResponseMessage> FileReceive1r(string id)
        {
            var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
            Stream stream = HttpContext.Current.Request.GetBufferlessInputStream(true);

            StreamReader rdr = new StreamReader(stream);
            while(!rdr.EndOfStream)
            {
                //FileStream fs = new FileStream(@"c:\sampl.zip", FileMode.OpenOrCreate);
                StreamWriter wrtr = new StreamWriter(new FileStream(@"c:\sampl.zip", FileMode.OpenOrCreate));
                wrtr.Write(rdr.ReadToEnd());
                wrtr.Close();
            }
            rdr.Close();
            return await Task.FromResult(new HttpResponseMessage(HttpStatusCode.Created));
        }

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码批量下载文件

public HttpResponseMessage Get()
        {
            string filename = @"c:\sampl.zip";

            var response = this.Request.CreateResponse();

            response.Content = new PushStreamContent(async (Stream outputStream, HttpContent content, TransportContext context) =>
            {
                try
                {
                    var buffer = new byte[65536];

                    using (var video = File.Open(filename, FileMode.Open, FileAccess.Read))
                    {
                        var length = (int)video.Length;
                        var bytesRead = 1;

                        while (length > 0 && bytesRead > 0)
                        {
                            bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                            await outputStream.WriteAsync(buffer, 0, bytesRead);
                            length -= bytesRead;

                        }
                    }
                }
                finally
                {
                    outputStream.Close();
                }
            });

            return response;
        }