[英]MVC C# Download file and save as dialog
大家好,想知道是否有人可以提供幫助; 我編寫了這段代碼,它將生成一個 excel 電子表格並將其保存到指定位置。 然后我想通過從存儲位置讀取文件然后詢問用戶他們想要存儲它的位置來顯示一個“另存為”對話框。 excel 文件生成良好,我可以正常打開它,但是我的問題是我編寫的代碼似乎直接將文件輸出到我的瀏覽器,所以我在瀏覽器屏幕上獲取了 excel 文件的所有內容,未按預期顯示另存為對話框!
public ActionResult FormSuccess()
{
String FileName = System.Configuration.ConfigurationManager.AppSettings["FileName"].ToString();
String FilePath = System.Configuration.ConfigurationManager.AppSettings["FileSaveLocation"].ToString();
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.xls";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.End();
return PartialView("FormSuccess");
}
喲文斯,技巧怎么樣? 還戴着勛章? :)
您不應該使用 FileContentResult 而不是 PartialView 嗎? You won't be able to return the file AND the HTML "success" content in the same call - you should probably call the PartialView first, which would then use javascript to open the FileContentResult URL in a new window.
看到這個: http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files
還有這個 url :
http://weblogs.asp.net/rajbk/archive/2010/05/03/actionresult-types-in-mvc2.aspx
我認為您的問題是您返回 PartialView。 讓我給你一個我的實現的小例子:
public ActionResult FileXls()
{
var output = new MemoryStream();
var writer = new StreamWriter(output);
//create your workbook excel file
....
//workbook.Save(output);
writer.Flush();
output.Position = 0;
return File(output, "text/excel", "file.xls");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.