5

I am trying to download a excel file through Web API (using Entity framework). The download is working but I am getting some error dialog about file corrupt when trying to open the file.

Web API code as below:

  public HttpResponseMessage GetValue(int ID, string name)
    {

    MemoryStream stream;
    try {
        using (DataContext db = new DataContext()) {
            dynamic fileObj = (from c in db.FileList c.ID == IDc).ToList();
            stream = new MemoryStream(fileObj(0).File);
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue(fileObj(0).FileContentType);
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = name };
            return result;
        }
    } catch (Exception ex) {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}

It opens the file with two error dialog and following message.

Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded

enter image description here

enter image description here

user2739418
  • 1,623
  • 5
  • 29
  • 51
  • Post upload file code. And a side note: returning InternalServerError on exception in unnecessary, it is web api default behavior. – ranquild Jun 19 '15 at 15:24
  • Did you ever resolve this? – Corpsekicker Jan 28 '16 at 06:27
  • Yes. I did resolve it. There was error in the code which was uploading the file to SQL Server. Download was correct. So fixed the upload and it was fine. Do you have similar problem? I can post the code if I can find. – user2739418 Feb 01 '16 at 15:12
  • 4
    I've the same problem. I'm generating the excel file using EPPlus. If I generate it in a console application and save it in file system the excel is working fine. If I send the same stream as HttpResponseMessage in web API I'm getting the same repair alert. Once you click yes, the excel opens fine. But I want to remove that alert. – NLV Aug 31 '16 at 18:33
  • Maybe error is with the upload! Can you paste the code for upload (web api)? I don't have old code now as it was done for one client – user2739418 Sep 02 '16 at 12:44
  • Five and a half years later... I have the same problem. I am creating the Excel file on the fly with EPPlus in my Web Api Controller, then downloading it with an HttpResponseMessage. I get 14KB of the expected 22KB.If I save the file to the file system first, the file is fine. The problem seems to be the chunking of the response and/or gzip. – Greg M. Mar 05 '21 at 19:06

2 Answers2

1

Trying to solve the same. I compared 2 epplus versions: 4.5.3.3 against 5.2.1. The latter one included a code for closing the stream in the GetAsByteArray procedure. So, I just added those lines to the 4.5.3.3 version and it worked like a charm. Looks like the stream initially included some garbage bites which must be deleted before pumping the file data into that stream. Tested with the NetCore 3.1 web application. Hope it will solve the issue in your case.

if (save)
{
    Workbook.Save();
    _package.Close();

    /* start of added code */
    if (_stream is MemoryStream && _stream.Length > 0)
    {
        CloseStream();
    }
    /* end of added code */

    _package.Save(_stream);
}

Lukan
  • 11
  • 2
0

I had the same issue, problem is not in the web api code, but it is in the client side code. For me i was using jquery. Following code fixed it for me.

I was creating a blob from the result, which is not required as, result is already a blob.

 window.URL.createObjectURL(result);

Note that i am creating object straight away from the result. Full Jquery code below.

Credit goes to mgracs in here

$.ajax({
                type: 'POST',
                url: url + "/download",
                data: data,
                xhr: function () {
                    var xhr = new XMLHttpRequest();
                    xhr.responseType = 'blob'
                    return xhr;
                },
                success: function (result, status, xhr) {
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }

                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(result);
                    link.download = filename;
                    link.click();

                }, error: function (a, b) {
                    console.log('Error');
                }
            });
RasikaSam
  • 5,363
  • 6
  • 28
  • 36