It's been a long time since I've written, and today I'm sharing a way to build a file using Ajax in ASP.net mvc, and here's the bottom of the story:
Everyone should know that in asp.net mvc, if you use Ajax to tune your back controller, 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 use Ajax to generate files and download them, So just save the generated files to the service, the file path is then returned via JSON before it can be downloaded, and, of course, it is temporarily stored, so it is necessary to delete the corresponding file when the download is complete.
Here's how to generate Excel as an example (the step-by-step procedure for generating Excel is omitted, which is not the point of this article):
1. First create action to generate Excel files
[HttpPost]
Public Jsonresult Exportexcel ()
{
DataTable dt = Dataservice.getdata ();
var fileName = "Excel_" + DateTime.Now.ToString ("yyyymmddhhmm") + ". xls";
Save the generated file in the presence of the waiter
string fullpath = Path.Combine (Server.MapPath ("~/temp"), fileName);
using (var exportdata = new MemoryStream ())
{
///How to build Excel It's not detailed to say that I'm using the Excel operation in this Npoi
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 filename return
Json (new {filename = filename, errormessage = ""});
}
2. Create a download Action
[HttpGet]
[Deletefileattribute]//action Filter, which automatically removes the file after downloading, which later explains the public
actionresult Download (string file)
{
/ /To download the file under the service file
string fullpath = Path.Combine (Server.MapPath ("~/temp"), file);
Returns the file image, which is used in Excel, so the file uses the "application/vnd.ms-excel" Return file
(FullPath, "application/vnd.ms-excel", files );
}
3. Create an Action Filter by automatically erasing the file after downloading it
public class Deletefileattribute:actionfilterattribute
{public
override void Onresultexecuted ( ResultExecutedContext filtercontext)
{
filterContext.HttpContext.Response.Flush ();
Convert the former filter context into a file that has been manipulated and obtain a file path
string filePath = (Filtercontext.result as Filepathresult). FileName;
There is a file path after you can delete the related files directly
System.IO.File.Delete (FilePath);
}
4. Finally, add Ajax-adjusted codes on the front:
Here I use Blockui to do loading
... $.blockui ({message: '