问题
I'm trying a lot of options with complete unsuccess. My need is create a spreadsheed in the server and the user gets it in the browser in a asp.net MVC 5 environment.
In the server the code is:
[HttpPost]
public ActionResult ExportToExcel([ModelBinder(typeof(DevExpressEditorsBinder))] Reports data)
{
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
ws.Cells["A1"].Value = "Sample 1";
ws.Cells["A1"].Style.Font.Bold = true;
var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
shape.SetPosition(50, 200);
shape.SetSize(200, 100);
shape.Text = "Sample 1 text text text";
if (data.PDFFileName == null) data.PDFFileName = "Spreadsheet.xlsx";
data.PDFFileName = Path.GetFileNameWithoutExtension(data.PDFFileName) + ".xlsx";
FileContentResult result = new FileContentResult(pck.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.FileDownloadName = data.PDFFileName;
return result;
}
The view is
@Ajax.ActionLink("Created Spreadsheet", "ExportToExcel", "GraphReport", null, new AjaxOptions { HttpMethod = "POST" }, new { @class="btn btn-warning" })
The result in Chrome is:
Remote Address:[::1]:49711
Request URL:http://localhost:49711/GraphReport/ExportToExcel
Request Method:POST
Status Code:200 OK
Response Headers
Cache-Control:private, s-maxage=0
Content-Disposition:attachment; filename=Spreadsheet.xlsx
Content-Length:3561
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date:Mon, 29 Jun 2015 22:54:38 GMT
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:5.2
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcbWNhc3Ryb1xEb2N1bWVudHNcVmlzdWFsIFN0dWRpbyAyMDEzXFByb2plY3RzXE1jU29mdFxDVlNcQmVlaGl2ZU1WQ1xHcmFwaFJlcG9ydFxFeHBvcnRUb0V4Y2Vs?=
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:31
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
The code is there in response:
PKÓÝFCjkh'¬[Content_Types].xmlµÛN!_eÃYh½0ÆtÛjb}f»¤ÂÐþ½,[ij¢I{5?3ß?f½5Õ#iï6åV¡^i·jØûò©¾e%p
wذ-æ³eª\ë¨a]JáNZ ´>ZHyW"\Ã
Why it is not being interpreted as download attached file?
回答1:
It's because you cannot download file via AJAX call.
Solution: Create a form, use the POST method, submit the form. When the server page responds to the request, write a response header for the mime type of the file, and it will present a download dialog. You may need to use an iframe
to prevent your site from navigating to error page if server returns an error.
Many of questions like this, they all have answers..
Ajax call to download file returned from RESTful service
Handle file download from ajax post
来源:https://stackoverflow.com/questions/31127060/why-the-browser-cant-show-an-epplus-spreadsheet