如何从 JavaScript 的 GET 请求中获取附件? (休息)
How to get an attachment from GET request with JavaScript? (REST)
我有一个带有 table 的网页,它从 XMLHttpRequest 生成一次。响应包括一个 JSON,其中包含一些文本和指向可能存在或不存在的三个附件的关联链接,因此我必须遍历这些以存储变量并创建链接,如下所示:
function drawWITable(tableObjArr) {
tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries.reverse();
var tableCount = Object.keys(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries).length;
var tableHeader = "<table><tr><th class='general'>ФИО</th><th class='general'>Примечания</th><th class='general'>Дата создания</th><th class='general'>Группа</th><th class='attch1'> </th><th class='attch2'> </th><th class='attch3'> </th></tr>";
var tableContent = "";
for(i = 0; i < tableCount; i++) {
tableContent = tableContent + "<tr class='hoverHL'><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.FullName + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Detailed Description"] + "</td><td>" + moment(Date.parse(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log Submit Date"])).format('dd, MMMM DD YYYY, HH:mm:ss') + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.DftSupportGroup + "</td>";
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName1 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment1(authToken, wrklgID, attachName1);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName2 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment2(authToken, wrklgID, attachName2);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName3 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment3(authToken, wrklgID, attachName3);'>" + "1" + "</td>";
}
tableContent = tableContent + "</tr>";
}
var tableFooter = "</table>";
document.getElementById("request-worklog").innerHTML = tableHeader + tableContent + tableFooter;
$("#request-worklog table tbody tr th").resizable({
minHeight: 20,
maxHeight: 20
});
}
然后,通过单击任一附件区域,用户应该能够下载文件。
function getAttachment1(authToken, wrklgID, attachName1) {
var data = "undefined=";
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open("GET", "http://XXXXXXXXXXXXXXXX/v1/entry/WOI:WorkInfo/" + wrklgID + "/attach/z2AF%20Work%20Log01", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Authorization", authToken);
request.setRequestHeader("Cache-Control", "max-age=0");
request.responseType = "blob";
request.send(data);
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
console.log(content);
}
};
}
现在点击后我只得到
形式的网络响应
PNG
IHDRrWؼøsRGB®ÎégAMA±üa pHYsÒÝ~ütIMEÞ,-ËòtEXtSoftwarepaint.net 4.0.9l3~NIDATx^íTÕÙÇMóK5Ý.Ò¤
R-Ö|ES±1*ÁìF£_H+±¤ÇXbÔ¨`OÑÙÙ]vvg]¶²Íóýÿï9çÎ;gª|qÞçù=sË9ï9÷üï©÷ÞÙI)ÕVfçn
©÷½2;ïmÝu
*zÀxU±ßF¦|fÈ(ÍÐÑa¢ÃÒì?F3b¬fä8Í£Æ&hFOb¬9ÈaÌ!±jÆf¤¸fBøÄÉ1-dWMdÄ{Ñe¶kÜÑ1æ
9Ö°Ìö±íTÈû«HóýcÌ#d¨]ÂN<as÷ á ûTðÑoôæ+çÄý0cÌ£/9ÉB>FU`TV[^aì¨o°&2èÂÄ4a"£ÄêÙsUÃ57ªæ_=¬Züj}êiµyÍêþêTÕ×NTlãäDö¢"}§0¼èqÒ|ô~qß=_%äÇbÌ#$âù«j{þÅ?>&àbOÑq{> qå*ã!j¿Á#e(ßpÃ-ª3Wïõô¸ó£ëª¬DØâ¦Ñ7W>1#ý©Mw.üµ>ýÅPß6Õ_?IÊ¡õñ§À*qÆ|=mÁ9¶u¯R-xLµ<ö¸æO?kW`áOñæg¤W(Æ!Yyµª·½]ÎZë®Ià\ö2CõvtÐÚÚÖ½¬çcYâ¨]uªM ]vñ|Ö¬W3ÏÍ+&k
o,Þ L´<ön=rÄsì1@uUWk½½ò\¼TûàyÔ¨¦Õ÷©Þ-[tÒÝ®®ª#5]?ý\Û6BJá6ßû .¤5ÐD*ÁV®ÎèGÓÒr´F1+'NõÏ"5.[.ïZrÉ5éBÞ{FBêÈã¶Òò$¢Ì޴ƧÌTïántmíKÞ»^Dì;Lµüù´Â}?ÖüУ(4sü{AjkÝUEÿüM3Ç
½m\ÎL7©AÓ
!ï{ äë©N·@}ÀBRDô'õHÖæMÓôHSÄ&-Gó»éÖÛuÁòMHúJ.½Á'HúÔp\Z!B¦]C6pmlZCi1WÈõI
BFær*ìì4¡µi!Cíļóå2ÌØS¿I5þr¥ªùÆéªrÖñàkØþ®jZuêÝÜì-Tk³¾/MHZOs3FÊèR¦Ç×êãNÚw"dâÔ³T|Ʊ*¡äW8N3óx
®Oº púbìRâ¢_ì®KfÔBÄoZ}¿´iÓ¢ #Ç©æGÁß±Ð+8÷tâæén¾Dý-ÿyÇ+"!«Ød2û¿\¸é1GH®ðó$"BþÄ;^!fMjÃÍ?òzQC]ù^úÜÌ»koÊ*fÝ%KtáØt)$¦PÙjr/
OÂéÔ-\ìo9%/¿:]Èû1p YyÄ1~·6Æ etc...
以及控制台中的这个:
Blob {size: 6698, type: "application/octet-stream"}
size: 6698
type: "application/octet-stream"
__proto__: Blob
接下来我该做什么?如何启动下载过程?我能够从另一端获得附件的名称,但仅此而已,没有类型或任何东西。官方文档也没什么帮助。我是 JS 的新手,所以也许我缺少一些简单的东西?
谢谢!
使用它来查看您的文件
let blob = new Blob([byteArray], {type: contentType});
var blobURL=URL.createObjectURL(blob);
window.open(blobURL);
获取内容后下载:
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
_html5Saver(content, 'myfile.png');
}
};
}
function _html5Saver(blob , fileName) {
// to emulate click action
// because we cannot save directly to client's computer due to security constraints
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
如果你想让浏览器下载图片而不是显示图片,你需要设置一个http header Content-Disposition: attachment。
而且你不应该使用 xhr,你应该跳转到 link.
我有一个带有 table 的网页,它从 XMLHttpRequest 生成一次。响应包括一个 JSON,其中包含一些文本和指向可能存在或不存在的三个附件的关联链接,因此我必须遍历这些以存储变量并创建链接,如下所示:
function drawWITable(tableObjArr) {
tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries.reverse();
var tableCount = Object.keys(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries).length;
var tableHeader = "<table><tr><th class='general'>ФИО</th><th class='general'>Примечания</th><th class='general'>Дата создания</th><th class='general'>Группа</th><th class='attch1'> </th><th class='attch2'> </th><th class='attch3'> </th></tr>";
var tableContent = "";
for(i = 0; i < tableCount; i++) {
tableContent = tableContent + "<tr class='hoverHL'><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.FullName + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Detailed Description"] + "</td><td>" + moment(Date.parse(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log Submit Date"])).format('dd, MMMM DD YYYY, HH:mm:ss') + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.DftSupportGroup + "</td>";
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName1 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment1(authToken, wrklgID, attachName1);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName2 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment2(authToken, wrklgID, attachName2);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName3 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment3(authToken, wrklgID, attachName3);'>" + "1" + "</td>";
}
tableContent = tableContent + "</tr>";
}
var tableFooter = "</table>";
document.getElementById("request-worklog").innerHTML = tableHeader + tableContent + tableFooter;
$("#request-worklog table tbody tr th").resizable({
minHeight: 20,
maxHeight: 20
});
}
然后,通过单击任一附件区域,用户应该能够下载文件。
function getAttachment1(authToken, wrklgID, attachName1) {
var data = "undefined=";
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open("GET", "http://XXXXXXXXXXXXXXXX/v1/entry/WOI:WorkInfo/" + wrklgID + "/attach/z2AF%20Work%20Log01", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Authorization", authToken);
request.setRequestHeader("Cache-Control", "max-age=0");
request.responseType = "blob";
request.send(data);
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
console.log(content);
}
};
}
现在点击后我只得到
形式的网络响应PNG
IHDRrWؼøsRGB®ÎégAMA±üa pHYsÒÝ~ütIMEÞ,-ËòtEXtSoftwarepaint.net 4.0.9l3~NIDATx^íTÕÙÇMóK5Ý.Ò¤
R-Ö|ES±1*ÁìF£_H+±¤ÇXbÔ¨`OÑÙÙ]vvg]¶²Íóýÿï9çÎ;gª|qÞçù=sË9ï9÷üï©÷ÞÙI)ÕVfçn
©÷½2;ïmÝu
*zÀxU±ßF¦|fÈ(ÍÐÑa¢ÃÒì?F3b¬fä8Í£Æ&hFOb¬9ÈaÌ!±jÆf¤¸fBøÄÉ1-dWMdÄ{Ñe¶kÜÑ1æ
9Ö°Ìö±íTÈû«HóýcÌ#d¨]ÂN<as÷ á ûTðÑoôæ+çÄý0cÌ£/9ÉB>FU`TV[^aì¨o°&2èÂÄ4a"£ÄêÙsUÃ57ªæ_=¬Züj}êiµyÍêþêTÕ×NTlãäDö¢"}§0¼èqÒ|ô~qß=_%äÇbÌ#$âù«j{þÅ?>&àbOÑq{> qå*ã!j¿Á#e(ßpÃ-ª3Wïõô¸ó£ëª¬DØâ¦Ñ7W>1#ý©Mw.üµ>ýÅPß6Õ_?IÊ¡õñ§À*qÆ|=mÁ9¶u¯R-xLµ<ö¸æO?kW`áOñæg¤W(Æ!Yyµª·½]ÎZë®Ià\ö2CõvtÐÚÚÖ½¬çcYâ¨]uªM ]vñ|Ö¬W3ÏÍ+&k
o,Þ L´<ön=rÄsì1@uUWk½½ò\¼TûàyÔ¨¦Õ÷©Þ-[tÒÝ®®ª#5]?ý\Û6BJá6ßû .¤5ÐD*ÁV®ÎèGÓÒr´F1+'NõÏ"5.[.ïZrÉ5éBÞ{FBêÈã¶Òò$¢Ì޴ƧÌTïántmíKÞ»^Dì;Lµüù´Â}?ÖüУ(4sü{AjkÝUEÿüM3Ç
½m\ÎL7©AÓ
!ï{ äë©N·@}ÀBRDô'õHÖæMÓôHSÄ&-Gó»éÖÛuÁòMHúJ.½Á'HúÔp\Z!B¦]C6pmlZCi1WÈõI
BFær*ìì4¡µi!Cíļóå2ÌØS¿I5þr¥ªùÆéªrÖñàkØþ®jZuêÝÜì-Tk³¾/MHZOs3FÊèR¦Ç×êãNÚw"dâÔ³T|Ʊ*¡äW8N3óx
®Oº púbìRâ¢_ì®KfÔBÄoZ}¿´iÓ¢ #Ç©æGÁß±Ð+8÷tâæén¾Dý-ÿyÇ+"!«Ød2û¿\¸é1GH®ðó$"BþÄ;^!fMjÃÍ?òzQC]ù^úÜÌ»koÊ*fÝ%KtáØt)$¦PÙjr/
OÂéÔ-\ìo9%/¿:]Èû1p YyÄ1~·6Æ etc...
以及控制台中的这个:
Blob {size: 6698, type: "application/octet-stream"}
size: 6698
type: "application/octet-stream"
__proto__: Blob
接下来我该做什么?如何启动下载过程?我能够从另一端获得附件的名称,但仅此而已,没有类型或任何东西。官方文档也没什么帮助。我是 JS 的新手,所以也许我缺少一些简单的东西?
谢谢!
使用它来查看您的文件
let blob = new Blob([byteArray], {type: contentType});
var blobURL=URL.createObjectURL(blob);
window.open(blobURL);
获取内容后下载:
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
_html5Saver(content, 'myfile.png');
}
};
}
function _html5Saver(blob , fileName) {
// to emulate click action
// because we cannot save directly to client's computer due to security constraints
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
如果你想让浏览器下载图片而不是显示图片,你需要设置一个http header Content-Disposition: attachment。 而且你不应该使用 xhr,你应该跳转到 link.