Search code examples
javascriptrestdownloadblob

How to get an attachment from GET request with JavaScript? (REST)


I have a web page with a table which generates once from a XMLHttpRequest. The response includes a JSON with some text and associated links to three attachments that may or may not be there, so I have to loop through those to store variables and create links, like so:

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
            });
            
        }

Then, by clicking either of the attachment areas user should be able to download file.

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);
        }
    };
  }

Right now after clicking I only get network response in form of

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ïánt­mí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...

As well as this in the console:

Blob {size: 6698, type: "application/octet-stream"}
size: 6698
type: "application/octet-stream"
__proto__: Blob

What should I do next? How to initiate the download process? I am able to get a name of an attachment from the other side, but that's it, no type or anything. Official documentation isn't much of a help either. I am fairly new to JS, so maybe it's something simple that I'm missing?


Solution

  • To download after getting the content:

    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);
    }