简体   繁体   中英

Returning a File read into MemoryStream for download in ajax C#

I created an Excel file in a C# application using OpenXML. I subsequently read it into a MemoryStream type. Now I want to return this file for download from the C# functions that returns an ActionResult Type. The data is returned to an ajax function where I am expecting a download prompt for the user so that they can save this file if they want. Below is some sample code and things I tried.

My aim with MemoryStream was that I don't need to store the above created physical file on the server. Is there a way to have the contents of the MemoryStream be returned to Ajax function for download?

I do not want to use TRIAL 3 where I sent the path of the file to ajax function where it uses it to redirect. This however works and I get the download message from the IE web browser. But nothing happens for Trial 1 or Trial 2 except perhaps Error.

Is it because I need to have a physical file on the server for it to be downloaded. Not sure if ajax code needs anything more for Trial 1 or Trial 2 to work.

Any tips on how I should be doing it the right way would be very helpful. Thanks

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

}

Ajax

$(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.");
            },
        });
    });
});

Good job showing your work.

When you're done putting content into memoryStream , its Position property will refer to the end of the stream. Reset it back to the beginning and you can read from it.

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

Then you can use the File method the way you wanted.

return File(memoryStream, mimeType, suggestedFileName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM