2014-05-14 261 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!"); 
    }