3

如果您能解释一下为什么 TransmitFile 不起作用,代码很简单,我创建 excel 文件 ( .xlsx),将其保存在服务器上并返回文件路径(通过 CreateProjectsReport),然后我只想获取文件并将其传输给用户。 ...

string filePath = CreateProjectsReport(ProjectIds, items);

System.IO.FileInfo file = new System.IO.FileInfo(filePath);

if (file.Exists)
{
    HttpContext context = HttpContext.Current;

    try
    {
        context.Response.Clear();
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.AddHeader("Content-Disposition", 
                                   "attachment; filename=" + file.Name);
        context.Response.AddHeader("Content-Length", file.Length.ToString());

        // context.Response.ContentType = "application
        // vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.TransmitFile(file.FullName);
        context.Response.Flush();
        // context.Response.WriteFile(file.FullName, false);                                
    }
    catch (Exception ex)
    {
        LogException(ex);
    }
    finally
    {
        System.IO.File.Delete(filePath);
        context.Response.End();
    }
}

此代码的结果是文件保存在我的服务器上的预期文件夹中(完整报告在那里,我验证了由方法生成的 excel 文件)并且response.Flush()我看到文件正在浏览器上传输,内容长度30kb为文件长度在服务器上,但是一旦我点击保存并且文件保存在我的下载文件夹中,它的长度是10kb,用excel打开它我得到错误:Excel foudn unreadable content in 'filename.xlsx'. Do you want to recover ....

检查 IIS MIME 类型,它已设置(我尝试将两者都用于内容类型,得到相同的错误):

.xls -application/vnd.ms-excel

.xlsx -application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

context.Response.TransmitFile 是否抑制我的文件并且不发送它的全部内容?为什么会这样?

编辑

通过浏览器控制台,我可以看到 inResponse.Header属性content-length是文件的确切长度,但是一旦我单击Save文件,该文件大小从 1kb 到 15kb 顶部,而不是服务器上的 30kb(就像TransmitFile(file.FullName)不传输整个文件

例子

4

0 回答 0