【问题标题】:Returning a File read into MemoryStream for download in ajax C#返回读取到 MemoryStream 的文件以在 ajax C# 中下载
【发布时间】: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.");
            },
        });
    });
});

【问题讨论】:

    标签: c# ajax


    【解决方案1】:

    很好地展示了你的作品。

    当您将内容放入memoryStream 后,其Position 属性将引用流的结尾。将其重置为开头,您可以从中读取。

    memoryStream = ReadDataIntoMemoryStream();
    memoryStream.Position = 0L;
    

    然后你可以按照你想要的方式使用File方法。

    return File(memoryStream, mimeType, suggestedFileName);
    

    【讨论】:

    • 感谢您的回复,但是我仍然无法看到文件下载。我相信这是我在上面发布的 ajax 代码中的特定内容。数据类型、内容类型或其他内容。除了 C# 代码返回一个字符串并使用 window.location.href 进行重定向之外,我想要做的可能是无法实现的。
    猜你喜欢
    • 2014-08-17
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多