如何從MVC控制器提供要下載的文件?在WebForms中,我通常會有這樣的代碼讓瀏覽器顯示一個“下載文件”彈出窗口,其中包含任意文件類型,如PDF和文件名:Response.Clear()Response.ClearHeaders()''# Send the file to the output streamResponse.Buffer = TrueResponse.AddHeader("Content-Length", pdfData.Length.ToString())Response.AddHeader("Content-Disposition", "attachment; filename= " & Server.HtmlEncode(filename))''# Set the output stream to the correct content type (PDF).Response.ContentType = "application/pdf"''# Output the fileResponse.BinaryWrite(pdfData)''# Flushing the Response to display the serialized data''# to the client browser.Response.Flush()Response.End()如何在ASP.NET MVC中完成相同的任務?
3 回答

慕少森
TA貢獻2019條經(jīng)驗 獲得超9個贊
要強制下載PDF文件,而不是由瀏覽器的PDF插件處理:
public ActionResult DownloadPDF(){ return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");}
如果您想讓瀏覽器按其默認行為(插件或下載)進行處理,只需發(fā)送兩個參數(shù)即可。
public ActionResult DownloadPDF(){ return File("~/Content/MyFile.pdf", "application/pdf");}
您需要使用第三個參數(shù)在瀏覽器對話框中指定文件的名稱。
當傳遞第三個參數(shù)(下載文件名)Content-Disposition: attachment;
被添加到Http響應標題。我的解決方案是application\force-download
作為mime類型發(fā)送,但是這會產(chǎn)生下載文件名的問題,因此需要第三個參數(shù)來發(fā)送一個好的文件名,因此無需強行下載。
- 3 回答
- 0 關注
- 610 瀏覽
添加回答
舉報
0/150
提交
取消