通过Web API下载Excel文件.腐败 [英] Excel File download through web api. Getting corrupt

查看:128
本文介绍了通过Web API下载Excel文件.腐败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Web API(使用Entity Framework)下载Excel文件.下载正在运行,但是尝试打开文件时出现有关文件损坏的错误对话框.

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代码如下:

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已完成文件级别的验证和修复.该工作簿的某些部分可能已被修复或丢弃

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

推荐答案

我遇到了同样的问题,问题不在Web api代码中,而是在客户端代码中.对我来说,我正在使用jQuery.以下代码为我修复了该问题.

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.

我正在根据结果创建一个Blob,这不是必需的,因为result已经是一个Blob.

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

 window.URL.createObjectURL(result);

请注意,我正在直接从结果中创建对象.完整的Jquery代码如下.

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

此处 strong>

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

这篇关于通过Web API下载Excel文件.腐败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆