Search code examples
c#asp.net-mvcgembox-spreadsheetasp.net-boilerplate

MVC/WebApi Stream from HTTPPostedFileBase


I am trying to a pass a stream from a HttpPostedFileBase to a service method without saving to disk.

//Controller Action
[HttpPost]
    public void Import()
    {
        if (Request.Files.Count == 0)
            return new HttpStatusCodeResult(404);

        var file = Request.Files[0];

        _departmentAppService.Import(file.InputStream);
    }

//Service Method
public string Import(Stream stream)
    {
        var excelFile = ExcelFile.Load(stream, LoadOptions.CsvDefault);
        var worksheet = excelFile.Worksheets[0];
        var jsonString = worksheet.ToJsonString();
        return jsonString;
    }

An error of "Property accessor 'ReadTimeout' on object 'System.Web.HttpInputStream' threw the following exception:'Timeouts are not supported on this stream.'" is thrown when the stream is passed to the method. Is there an idiomatic method of doing this?


Solution

  • I was not able to reproduce this issue so I cannot inspect the stack trace that you get, but nevertheless I presume you get timed out because you're processing large CSV file in which case I would try to increase the 'executionTimeout' in web.config.

    Also you could try using a temporary memory stream to store an uploaded file, something like the following:

    var file = Request.Files[0];
    using (var tempStream = new MemoryStream())
    {
        file.InputStream.CopyTo(tempStream);
        tempStream.Position = 0;
        _departmentAppService.Import(tempStream);
    }
    

    I hope this helps.