【发布时间】:2018-12-11 05:34:26
【问题描述】:
我使用 OpenXML 在 C# 应用程序中创建了一个 Excel 文件。我随后将其读入 MemoryStream 类型。现在我想从返回 ActionResult 类型的 C# 函数中返回此文件以供下载。数据将返回到一个 ajax 函数,我希望用户在该函数中出现下载提示,以便他们可以根据需要保存此文件。下面是一些示例代码和我尝试过的东西。
我使用 MemoryStream 的目的是我不需要将上面创建的物理文件存储在服务器上。有没有办法将 MemoryStream 的内容返回给 Ajax 函数以供下载?
我不想使用 TRIAL 3,我将文件的路径发送到 ajax 函数,它使用它来重定向。然而,这可行,我从 IE 网络浏览器获得下载消息。但是对于 Trial 1 或 Trial 2,除了可能出现错误之外,什么都没有发生。
是不是因为我需要在服务器上有一个物理文件才能下载它。不确定 ajax 代码是否需要更多内容才能使试用 1 或试用 2 正常工作。
任何关于我应该如何以正确方式进行操作的提示都会非常有帮助。谢谢
public ActionResult createFile()
{
...
// Reads a file into memory stream. Common for all trials below
memoryStream = ReadDataIntoMemoryStream();
// TRIAL 1
FileStream fs= new FileStream();
memoryStream.CopyTo(fs);
string mimeType = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet";
return File(fs, mimeType);
// TRIAL 2
string mimeType = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet";
byte[] fileBytes = memoryStream.ToArray();
return File(fileBytes, mimeType);
// TRIAL 3
string filepath = "..\...\..\filename.xlsx"; // actual physical file on
// the server
return Content(filepath);
}
阿贾克斯
$(document).ready(function () {
$('#777').on('click', function () {
$.ajax({
method: "GET",
url: "Report/createFile",
contentType: "application/download", // not needed for Trial 3
// where string is returned
dataType:"text",
success: function (data) {
// window.location.href = data; // THIS WORKS with TRIAL 3
// where filepath is returned
},
error: function (data) {
alert("Error.");
},
});
});
});
【问题讨论】: