gpt4 book ai didi

javascript - 二进制 XHR 结果到文件 blob - Jquery

转载 作者:行者123 更新时间:2023-11-30 16:30:50 25 4
gpt4 key购买 nike

下载文档的 Web 服务返回以下内容:

%PDF-1.5
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 14 0 R/MarkInfo<</Marked true>>>>
endobj
2 0 obj
<</Type/Pages/Count 1/Kids[ 3 0 R] >>
endobj
3 0 obj
<</Type/Page/Parent 2 0 R/Resources<</Font<</F1 5 0 R/F2 8 0 R>>/ExtGState<</GS7 7 0 R>>/ProcSet[/PDF
/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 595.32 841.92] /Contents 4 0 R/Group<</Type/Group/S/Transparency
/CS/DeviceRGB>>/Tabs/S/StructParents 0>>
endobj
4 0 obj

要将此数据转换为文件,我使用以下代码:

$.ajax({
url: "/documents/docDownload",
type: "GET",
async: true,
headers: {
responseType: "arraybuffer"
},
success: function(data,status,xhr) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = data.name || "newPDF2";
document.body.appendChild(a);
a.click();
$(window).on('focus', function(e) {
$('a').remove();
});
}
})

函数返回一个 pdf 文件,但是当我打开 pdf 文件时,它是空的,似乎在转换过程中丢失了信息。

有人知道为什么会这样吗?

PHP - 网络服务代码

$path = "/xxx/xxx/xxx/xxx/work.pdf";
$res = $app->response();
$res['Content-Description'] = 'File Transfer';
$res['Content-Type'] = 'application/force-download';
$res['Content-Type'] = 'application/pdf';
$res['Content-Disposition'] ='attachment; filename=' . basename($path);
$res['Content-Transfer-Encoding'] = 'binary';
$res['Expires'] = '0';
$res['Cache-Control'] = 'must-revalidate';
$res['Pragma'] = 'public';
$res['Content-Length'] = filesize($path);
readfile($path);

最佳答案

所以,正如我所料。你们只是学不会 - jQuery 对于复杂的 XHR 来说不是一个好主意。他们有比继续实现很少使用的 XHR 调整更重要的任务。

问题是当接收到的数据被转换为字符串时,它被转换为 UTF-8,长度增加并变得损坏:

image description

我们需要得到一个字节数组,我认为这就是您尝试使用 responseType: "arraybuffer" 的目的。但这不应该是标题。服务器不关心你如何转换接收到的数据。这是您设置它的方式:

var r = new XMLHttpRequest();
r.open("GET", ".../test.pdf");
// This configures how the data is parsed
r.responseType = "arraybuffer";
r.onload = function() {
var file = new Blob([this.response], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = "newPDF2";
document.body.appendChild(a);
a.click();
$(window).on('focus', function(e) {
$(a).remove();
});
}
r.send();

这行得通。另外,如果你想设置文件名,要么从 url 中解析它,如下所示:

var file_name = ".../test.pdf".match(/(^|\/)[^/]+$/)[2];

或者发送一个正确的文件名头并解析它:

var file_name = this.getResponseHeader("Content-Disposition").match(/filename=(.*?)$/)[1];

不过我还是不明白为什么不强制从服务器下载...

关于javascript - 二进制 XHR 结果到文件 blob - Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com