0

Is there any way to implement a .net Web api to receive a lrage file(>2gb) using bufferlessinput stream without multipart/form-data mime type?

I am trying to do it with below code, but its not reading the stream completely. I am trying to upload 100 MB file, but it writes only 10MB to "c:\sampl.zip" and comes out. what went wrong in below code?

        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));
        }
Thavudu
  • 235
  • 3
  • 13
  • 1
    yep. as long as you have enough memory. just use a stream. – Daniel A. White Jun 28 '18 at 01:42
  • I get a stream as soon as as content started streaming through var stream = HttpContext.Current.Request.GetBufferlessInputStream(true); But how to read it continiously until the last byte received in the stream. If I use stream.CopyToAsync(), it reads only some data and discards the stream. Any suggestion? – Thavudu Jun 28 '18 at 03:06

1 Answers1

0

You can use following code to download the file in chunk

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;
        }