[英].net Core send xlsx file as response for Ajax request
My web-application can only work with .xlsx-files.我的网络应用程序只能使用 .xlsx 文件。 I created a function in my controller, which converts a .xls-file into an .xlsx-file.
我在控制器中创建了一个函数,它将 .xls 文件转换为 .xlsx 文件。 The conversion works totally fine.
转换工作完全正常。 So whenever I try to open a .xls-file, I send it via Ajax request.
因此,每当我尝试打开一个 .xls 文件时,我都会通过 Ajax 请求发送它。
After that, I want to respond with the converted .xlsx-file, but it never arrives at the client.之后,我想用转换后的 .xlsx 文件进行响应,但它永远不会到达客户端。
Since the conversion works fine, i simplified the code, to just pass a simple .xlsx file, which didn't work aswell.由于转换工作正常,我简化了代码,只传递一个简单的 .xlsx 文件,该文件也不起作用。
JavaScript: JavaScript:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
formData = new FormData();
formData.append("xlsfile", files[0]);
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: formData,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
Controller:控制器:
public IActionResult ConvertToXlsx(IFormFile xlsfile) {
//For simplification without conversion
//var xlsconverter = new XLSConverter();
//FileStreamResult response = xlsconverter.XLSConvert(xlsfile);
var path = $"wwwroot/temp/";
var filepath = Path.Combine(path, "test.xlsx");
MemoryStream x = new MemoryStream();
using(FileStream fs = System.IO.File.OpenRead(filepath)) {
fs.CopyTo(x);
}
return File(x, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
In the browser-network tab I get Status: net::ERR_CONNECTION_RESET在浏览器网络选项卡中,我得到状态:net::ERR_CONNECTION_RESET
Am I missing a setting somewhere, which causes I simply can't respond with files?我是否在某处遗漏了某个设置,导致我根本无法响应文件?
If you want to pass file to action,try to use the following code:如果要将文件传递给操作,请尝试使用以下代码:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: files[0],
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
And if you want to return file with content type,you can try to use:如果你想返回内容类型的文件,你可以尝试使用:
public IActionResult ConvertToXlsx(IFormFile xlsfile)
{
return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.