在类似的问题中,使用此代码可以下载 PDF:
I'm testing with local files (.xlsx, .pdf, .zip) inside the Controller folder.
[HttpGet("downloadPDF")]
public FileResult TestDownloadPCF()
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult
(System.IO.File.ReadAllBytes("Controllers/test.pdf"), "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
但是当另一个文件?例如 Excel 文件 (.xlsx) 或 ZIP 文件 (.zip) 时,测试无法正常进行。
代码:
[HttpGet("downloadOtherFile")]
public FileResult TestDownloadOtherFile()
{
HttpContext.Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("Controllers/test.xlsx"),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "otherfile"
};
return result;
}
我还使用以下 Content-Type 进行了测试:
- “应用程序/vnd.ms-excel”
- “应用程序/vnd.ms-excel.12”
得到相同的结果。
返回任何文件类型的正确方法是什么?
感谢您的回答
最佳答案
我的(工作)解决方案:
- 我有一个使用 EPPlus.Core 动态创建 XLSX 文件的类。
- 这将返回生成文件路径的
FileInfo
。
- 这将返回生成文件路径的
这是我的 Controller 中的内容:
[HttpGet("test")]
public async Task<FileResult> Get()
{
var contentRootPath = _hostingEnvironment.ContentRootPath;
// "items" is a List<T> of DataObjects
var items = await _mediator.Send(new GetExcelRequest());
var fileInfo = new ExcelFileCreator(contentRootPath).Execute(items);
var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.ContentType = contentType;
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
var fileContentResult = new FileContentResult(bytes, contentType)
{
FileDownloadName = fileInfo.Name
};
return fileContentResult;
}
这是我在 Angular2 中的内容:
downloadFile() {
debugger;
var headers = new Headers();
headers.append('responseType', 'arraybuffer');
let url = new URL('api/excelFile/test', environment.apiUrl);
return this.http
.get(url.href, {
withCredentials: true,
responseType: ResponseContentType.ArrayBuffer
})
.subscribe((response) => {
let file = new Blob([response.blob()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
let fileName = response.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1];
saveAs(file, fileName);
},
err => this.errorHandler.onError(err)
);
}
关于c# - 如何从 ASP.NET Core Web API web-app 返回 Excel 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877195/