Using an AJAX-generated Excel file and downloading

Source: Internet
Author: User
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: ' 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.