2014-05-14 226 views
2

节省服务器的文件我读Luchian的建议此链接下载Excel中通过AJAX MVC文件,而无需在ASP.Net/C#

Download Excel file via AJAX MVC

对我真的很喜欢他的想法非常多这样我能避免可能会保存电子表格的2份副本。 或者不必担心在AJAX调用返回之前删除在服务器上保存的初始文件。

因此,如果我将电子表格保存为内存流并将其插入到唯一的缓存变量cache_uniq1中并在AJAX调用中返回该变量,那么我将如何打开该流?

我可以只做window.open吗?

$.ajax({  
    type: 'POST',  
    url: '/Reports/Somepage.aspx',  
    data: '{ "dataprop1": "test", "dataprop2" : "test2" }',  
    //contentType: 'application/json; charset=utf-8',  
    //dataType: 'json',  
    success: function (returnValue) { 

     //window.location = /Reports/Download?file=' + returnValue;  
     //  
     //NOTE: Instead the returnValue = cache_uniq1 which is the unique Cache  
     //variable name that holds the Excel spreadsheet as a memory stream 
    } 
}); 

任何帮助,非常感谢。仅供参考,我的应用程序是ASP.Net Web站点上的直接应用程序(不使用MVC)。

+0

尝试此链接... http://filamentgroup.com/lab/jquery-plugin-for-requesting-ajax-like-file-downloads.html GR8的工作对我来说 –

+0

这不工作我的情况。 – user428602

回答

0
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] 
    [Authorize] 
    public ActionResult DownloadExportedFile(string filename = null) 
    { 
     if (!String.IsNullOrEmpty(filename)) 
     { 
      var tempDirPath = System.IO.Path.GetTempPath(); 

      if (System.IO.File.Exists(tempDirPath + filename)) 
      { 
       var bytes = System.IO.File.ReadAllBytes(tempDirPath + filename); 

       System.IO.File.Delete(tempDirPath + filename); 

       var cd = new System.Net.Mime.ContentDisposition 
       { 
        FileName = Path.GetFileName("BookingForm.csv"), 

        // always prompt the user for downloading, set to true if you want 
        // the browser to try to show the file inline 
        Inline = false 
       }; 

       //Response.AppendHeader("Content-Disposition", cd.ToString()); 

       return File(bytes, "text/csv", "BookingForm.csv"); 
      } 
     } 

     return new HttpStatusCodeResult(404, "File not found!"); 
    }