javascript - 无法将文件从控制器操作发送到浏览器进行下载
问题描述
我正在向 a 发送 a XMLHttpRequest
,MVC Controller
因此我希望收到一个文件。使用浏览器进行调试时,我得到了一个没问题的response
结果,但我不知道为什么它不是一个文件:
JS
window.submit=function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response); //response looks ok...but no file starts downloading
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
控制器
[HttpPost]
[Route([Some Route])]
public async Task BenchAsync(object request)
{
try
{
string fileName = "results.txt";
object result = await service.RunAsync(request);
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
this.Response.ContentType = "application/octet-stream";
this.Response.ContentLength = data.Length;
using(MemoryStream stream=new MemoryStream(data))
{
await stream.CopyToAsync(this.Response.Body);
}
}
catch (Exception ex)
{
throw;
}
}
解决方案
多亏了这篇文章,我已经解决了
看来我必须将响应转换为BLOB
,创建一个下载链接并将其指向此 blob 和创建的链接才能下载文件。
所以函数看起来像:
window.submit= function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
var blob = new Blob([this.response], { type: 'image/pdf' });
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'mytext.txt';
a.click();
window.URL.revokeObjectURL(url);
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
PS我不知道 blob 的类型是什么,txt
但如果扩展名正确,它也可以工作。
推荐阅读
- spring - DeferredResult 用于两个不同的休息应用程序之间的异步处理
- python - 元组列表:仅根据第一个或第二个位置的公共元素选择元组
- javascript - 无法在我的计算机上使用 javascript 打印“hello world”消息
- excel - 更新 W64 VBA 的声明语句 PtrSafe 属性
- python - 在 Python 中使用 pivot_table 处理复杂的数据转换
- sql - 如何从 Azure SQL 数据库中的所有表中删除所有行?
- swift - Swift Cocoa App The application can't be opened
- python - 使用'is'运算符比较python中的两个字符串切片
- migration - 迁移到新服务器后的路径问题
- python - 如何在python中使用正则表达式根据值打印界面的整行