我正在嘗試使用打開/保存選項將csv
文件導出到用戶。MVC 4導出爲CSV - 另存爲對話框在Chrome和Firefox中不起作用
我的問題是一些什麼類似於how-to-force-chrome-to-open-an-open-file-dialog-when-downloading-a-file-via-as(It is downloading the file in Chrome and Firefox)
,我試過了@Dev
建議的解決方案,但它不工作。
,我寫我的代碼如下: -
return File(new System.Text.UTF8Encoding().GetBytes(csvData),
"text/csv", filename);
但是,它並沒有在Chrome中工作。該文件默認情況下正在下載。
然後谷歌搜索後,我發現returning-a-file-to-view-download-in-mvc,從中我試圖做類似如下: -
var csvData = "hello";// I am filling this variable with ,y values from DB!
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = "test",
Inline = false,
};
Response.AppendHeader("Content-Disposition",
cd.ToString());
return File(new System.Text.UTF8Encoding().GetBytes(csvData),
"text/csv");
,但仍然有人在下載Chrome瀏覽器中的文件。然後我碰到了how-to-display-open-save-dialog-asp-net-mvc-4,其中@JoãoSimões
提及爲: -
這是依賴於瀏覽器。如果您將自動下載到 給定文件夾,瀏覽器將自動下載。 Firefox和 Chrome是這種行爲的一些瀏覽器。 - 若昂·西蒙斯1月3日在 13:09
如果上述屬實,那我怎麼才能克服我的問題?我如何獲得打開/保存對話? 我無法導出我的CSV與打開/保存選項。
編輯1
我試圖做這樣的事情(有它here): -
public class ExcelResult : ActionResult
{
public string FileName { get; set; }
public string Path { get; set; }
public string Data { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Buffer = true;
context.HttpContext.Response.Clear();
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.ContentType = "text/csv";
context.HttpContext.Response.Write(new System.Text.UTF8Encoding().GetBytes(Data));
}
}
和我的控制器代碼: -
return new ExcelResult
{
FileName = "sample.xls",
Path = "",
Data = csvData
};
但儘管如此,它正在下載Excel ...
編輯2
試圖與HttpContext.Current.Response
/// <summary>
/// Export CSV
/// </summary>
/// <returns></returns>
public void DownloadCSV()
{
try
{
var csvData = Session["CSVData"].ToString();
byte[] getContent = new System.Text.UTF8Encoding().GetBytes(csvData);
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Buffer = true;
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "testing.csv");
System.Web.HttpContext.Current.Response.BinaryWrite(getContent);
System.Web.HttpContext.Current.Response.Flush();
}
catch (Exception ex)
{
HttpResponseMessage message = new HttpResponseMessage()
{
Content = new StringContent("Error Exporting Data")
};
throw new System.Web.Http.HttpResponseException(message);
}
}
但打開Excel中,仍然沒有工作!
從[this](http://www.andrewpatton.com/countrylist.csv)等任何其他頁面下載csv/xls文件時,是否顯示打開/保存對話框?如果沒有,這可能不是你的代碼,但與瀏覽器設置。 – developer10214
@ developer10214: - 您發佈的鏈接,我正在收到對話框。我想那麼無論是我的代碼問題或一些外星人的攻擊! 我還在摸頭.. – Shubh
你的代碼非常好。這取決於瀏覽器設置。沒有辦法解決這個問題,你不能/不應該試圖覆蓋用戶的瀏覽器設置,因爲它會像黑客機器一樣。 – Poornima