使用 JavaScript。我正在向服务器发送一个 xhr 请求,所以我收到一个 xhr 响应,其中包含多部分数据,第二部分包含可下载文件(pdf、png、office 文档)
在 xhr.response 我得到了这个:
--_NextPart_000_0002_01C3E1CC.3BB37320
Content-type: application/xml; charset=UTF-8
<ns0:sendAttachmentOutput xmlns:ns0="http://****/webservices/definition/BDS/AttachmentFileStorage/sendAttachmentOutput/1">
<ns0:msgCode>BDS0000</ns0:msgCode>
<ns0:msgLibelle>Pièce jointe envoyée</ns0:msgLibelle>
</ns0:sendAttachmentOutput>
--_NextPart_000_0002_01C3E1CC.3BB37320
Content-disposition: attachment; filename="testsza.xlsx"
Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
PK ! |lؖl [Content_Types].xml ( ]Kðǯ��4٦Ɉ珈Ω֦!'ܛ࠷4zԐ杷}Ҵ఼jLքZق��`KǴݕ�՟ҌôJg k@6]^ȫّÕ1̡҈݇K3Ջ͌��̲.g ޞͨݍ`c[
6>@%&fϫ`ѥ��̠ӻċʔ,κ擯8uƚ̵ǫàÓ]��Ԃl"C|֍aȕ.͟ݛԮ˴ ʕˆv# ֠ѱ<ͼҚi蟙ŝ_>ң�����$I爁`\3ж#z̹ցիԔgĮѤ8ϔ(N߅]d՝٧!Qþ4ڮࠞҒ鵃oןڼS:݅˗ѧ ��PK ! ֕0#��L _rels/.rels ( ̒ЎðǯH݃弪nHe܌HۡT$ͣ$@��Êcܑ��[߮窔b/Nú(Aѳb{تx͟Vb"giǚΜaWޞl_xĔܢػȲˋڔ��OѰQˡhѓɥܔ彆ߞP-<ցj{ʾ״Mox/羢؎̀ޓ;̶愦ʏۨۂ̉Õʻ"cަۜO��q"KʐHߊs@쫁.ࠨʸގ<⧄⎤T_ ��PK ! މ�� ԃ xl/_rels/workbook.xml.rels ( ܓЪðǯýđ}qӮeԺAЛ��㑄6'o?ԃۀɮWä��ȽᨯėjޕХ)ԥۨ̚<àֶҝӨ`@ÃqؿĎs$%Ǚ襤Ӡϩqmݔ.��궹֍ʼMײ��ƩΕð̶ NÏ
--_NextPart_000_0002_01C3E1CC.3BB37320
我想提取从 PK 开始的二进制数据。
这是我写的代码:
xhr.responseType = "arraybuffer";
xhr.onload = function (e) {
var arraybuffer = xhr.response;
var fileArray = new Uint8Array(arraybuffer);
var type = xhr.getResponseHeader('Content-Type');
var boundary;
if (type.indexOf('boundary') != -1) {
boundary = type.substring(type.indexOf('boundary') + 9);
}
var temp = holder.split('--' + boundary);
var parts = [];
//loop through array to remove empty parts
for (var i = 0; i < temp.length; i++) {
if (temp[i] != "") {
parts.push(temp[i]);
}
}
var type = parts[2].substring(parts[2].lastIndexOf('Content-type: ') + 14, parts[2].indexOf('\n', parts[2].lastIndexOf('Content-type: ')) - 1);
var filename = parts[2].substring(parts[2].indexOf('Content-disposition: attachment; filename="') + 43, parts[2].indexOf('\n', parts[2].indexOf('Content-disposition: attachment; filename="')) - 2);
var lastBoundary = holder.lastIndexOf(boundary) - 4;
//PARSE SECOND PART
//var fileStart = holder.indexOf('Content-disposition: attachment; filename="') + 43 + filename.length + 5;
//***** fileStart 应该有二进制数据开始的索引,否则它应该从 'PK' 开始,就在 content-type 行之后
//start point to the end of the array
var file = fileArray.buffer.slice(fileStart, lastBoundary);
if (!file || 0 === file.byteLength) {
_displayError("Pdf introuvable");
}
else if (type == "text/html;charset=UTF-8") {
_displayError("Erreur de téléchargement du pdf. Veuillez contacter l'administrateur.");
}
else {
var blob = new Blob([file],
{
type: type
});
我怎样才能做到这一点?