在类似的问题中,使用此代码可以下载PDF:
我正在使用Controller文件夹中的本地文件(.xlsx,.pdf,.zip)进行测试。
[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;
}
我还使用以下内容类型进行了测试:
获得相同的结果。
返回任何文件类型的正确方法是什么?
感谢您的回答
答案 0 :(得分:4)
我的(工作)解决方案:
FileInfo
。这是我的控制器中的内容:
[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)
);
}
答案 1 :(得分:2)
我有同样的问题。我的问题是由客户端请求引起的,不服务器响应。我通过在我的Get请求标题选项中添加响应内容类型来解决它。这是我在Angular 2中的例子。
来自客户端的请求(Angular 2)**需要filesaver.js库
ERROR in ./static/css/styles.css
Module parse failed: D:\work\simpleLeafLet\static\css\styles.css Unexpected token (2:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:0)
服务器端代码。 (.net核心)
this._body = '';
let rt: ResponseContentType = 2; // This is what I had to add ResponseContentType (2 = ArrayBuffer , Blob = 3)
options.responseType = rt;
if (url.substring(0, 4) !== 'http') {
url = config.getApiUrl(url);
}
this.http.get(url, options).subscribe(
(response: any) => {
let mediaType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
let blob = new Blob([response._body], { type: mediaType });
let filename = 'test.xlsx';
fileSaver.saveAs(blob, filename);
});
如果你想看,这里有参考文献。
答案 2 :(得分:0)
以下是如何下载文件的示例,您可以建模下载Excel文件的方案:
public IActionResult Index([FromServices] IHostingEnvironment hostingEnvironment)
{
var path = Path.Combine(hostingEnvironment.ContentRootPath, "Controllers", "TextFile.txt");
return File(System.IO.File.OpenRead(path), contentType: "text/plain; charset=utf-8", fileDownloadName: "Readme.txt");
}
如果文件位于wwwroot
文件夹中,您可以执行以下操作:
public IActionResult Index()
{
return File(virtualPath: "~/TextFile.txt", contentType: "text/plain; charset=utf-8", fileDownloadName: "Readme.txt");
}
答案 3 :(得分:0)
您可以使用NPOI
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.IO;
namespace export_excel.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExportExcelController : ControllerBase
{
private readonly IHostingEnvironment _hostingEnvironment;
public ExportExcelController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
// https://localhost:5001/ExportExcel/Export
// https://localhost:5001/static-file/employee.xlsx
[HttpGet]
[Route("Export")]
public IActionResult Export()
{
List<Employee> list = new List<Employee>()
{
new Employee{ emp_code = "152110032", Name = "Nguyen Hong Anh", Phone = "0909998789" },
new Employee{ emp_code = "152110055", Name = "Tran Phuong Dung", Phone = "0909993456" },
new Employee{ emp_code = "152110022", Name = "Do Bich Ngoc", Phone = "0909991237" },
new Employee{ emp_code = "152110025", Name = "Tran Thu Ha", Phone = "0909990987" },
};
// New workbook.
XSSFWorkbook wb = new XSSFWorkbook();
// New worksheet.
ISheet sheet = wb.CreateSheet();
// Write to sheet.
// Tạo row
var row0 = sheet.CreateRow(0);
// At first row, merge 3 columns.
// Create cell before merging.
row0.CreateCell(0);
CellRangeAddress cellMerge = new CellRangeAddress(0, 0, 0, 2);
sheet.AddMergedRegion(cellMerge);
row0.GetCell(0).SetCellValue("Employee information");
// Ghi tên cột ở row 1
var row1 = sheet.CreateRow(1);
row1.CreateCell(0).SetCellValue("emp_code");
row1.CreateCell(1).SetCellValue("fullname");
row1.CreateCell(2).SetCellValue("Phone");
// Traversaling array, then write continous.
int rowIndex = 2;
foreach (var item in list)
{
// Init new row.
var newRow = sheet.CreateRow(rowIndex);
// set values.
newRow.CreateCell(0).SetCellValue(item.emp_code);
newRow.CreateCell(1).SetCellValue(item.Name);
newRow.CreateCell(2).SetCellValue(item.Phone);
// Increase index.
rowIndex++;
};
if (!System.IO.File.Exists("c:\\myfiles\\employee.xlsx"))
{
FileStream fs = new FileStream(@"c:\myfiles\employee.xlsx", FileMode.CreateNew);
wb.Write(fs);
}
var path = Path.Combine(@"c:\myfiles\employee.xlsx");
return File(System.IO.File.OpenRead(path), contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8", fileDownloadName: "employee.xlsx");
}
}
public class Employee
{
public string emp_code;
public string Name;
public string Phone;
}
}
文件Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using System.IO;
namespace export_excel
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
// Path.Combine(env.ContentRootPath, @"c:\audio\")),
// Path.Combine(@"c:\audio\")),
Path.Combine(@"c:\myfiles")),
RequestPath = "/static-file"
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
您可以使用2种方法之一,转到
https://localhost:5001/ExportExcel/Export
或
https://localhost:5001/static-file/employee.xlsx