You should know that in ASP. NET MVC, if you go through Ajax, you can return a JSON image, but you can't return the file directly (unless you refresh the page, it's not Ajax), so if you want to generate the file and download it with Ajax, That is, if you save the generated file to the server first, and then the file path through the JSON back, then it can be downloaded, when it is temporarily stored, so when the download will need to delete the corresponding file.
The following is an example of how to generate excel in an instance (the step of generating Excel I omitted, which is not the point of this article):
1. First create an action to generate an Excel file
[Httppost]public jsonresult Exportexcel () { DataTable dt = Dataservice.getdata (); var fileName = "Excel_" + DateTime.Now.ToString ("yyyymmddhhmm") + ". xls"; Save the resulting file to the server's timeline string fullPath = Path.Combine (Server.MapPath ("~/temp"), fileName); using (var exportdata = new MemoryStream ()) { //How to generate Excel this will not be detailed and I am using Npoi for Excel in this operation. Utility.writedatatabletoexcel (DT, ". xls", exportdata); FileStream file = new FileStream (FullPath, FileMode.Create, FileAccess.Write); Exportdata.writeto (file); File. Close (); } var errormessage = "Can return the errors in here!"; Returns the generated file name return Json (new {filename = filename, errormessage = ""});
2. Create a download Action
[HttpGet] [Deletefileattribute]//action Filter, after downloading the auto delete file, this is a minor explanation of public actionresult Download (string file) { // To the server at the time of the file to download the corresponding file string fullPath = Path.Combine (Server.MapPath ("~/temp"), file); Return file to the image, this is used in Excel, so the file head used "application/vnd.ms-excel" return Files (fullPath, "application/vnd.ms-excel", File );}
3. Create an Action Filter by deleting the file automatically after downloading.
public class deletefileattribute:actionfilterattribute{public override void Onresultexecuted ( ResultExecutedContext filtercontext) { filterContext.HttpContext.Response.Flush (); Convert the former filter context into a file with the file path string filePath = (Filtercontext.result as Filepathresult). FileName; File path can be deleted directly after the relevant files System.IO.File.Delete (FilePath); }}
4. Finally add the code for Ajax in the front:
I used Blockui to do Loading...$.blockui ({message: '