将Blob转换为文件并在浏览器上预览(不下载)

时间:2018-08-11 03:02:38

标签: javascript pdf blob

我从Web服务标注中获取了Blob内容,要求在浏览器中显示该文件。

我所拥有的:

  • Blob文件(fileBlob)

在blob参数上方,我将其作为响应并将其发送回“回调”中的javascript方法。我正在尝试将Blob转换为相应的文件格式并在浏览器上查看(除非最终用户希望,否则我不想下载)。

我在下面尝试过

    var callback1 = { 
        onSuccess: function(e){ //e is the blob content I am receiving
            alert('Receiving file from SF:---> ' + e);
            var file = new File([e], "uploaded_file.pdf", { type: "application/pdf", lastModified: Date.now() });
            //document.body.append(file);
            //var blob=new Blob([e], {type:"application/pdf"});
            var link=document.createElement('a');
            //link.href=window.URL.createObjectURL(e);
            link.download=file;
            link.click();                

        }, onFailure: function(error){
            alert(error);   
        } 
    };

更新 enter image description here

更新2 (将响应视为base64之后) enter image description here

1 个答案:

答案 0 :(得分:5)

使用iframe来显示pdf文件,该函数看起来像这样,并带有blob响应和文件名。

   function openPDF(resData, fileName) {
            var ieEDGE = navigator.userAgent.match(/Edge/g);
            var ie = navigator.userAgent.match(/.NET/g); // IE 11+
            var oldIE = navigator.userAgent.match(/MSIE/g); 
            var bytes = new Uint8Array(resData); //use this if data is raw bytes else directly pass resData
            var blob = new window.Blob([bytes], { type: 'application/pdf' });

            if (ie || oldIE || ieEDGE) {
               window.navigator.msSaveBlob(blob, fileName);
            }
            else {
               var fileURL = URL.createObjectURL(blob);
               var win = window.open();
               win.document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')

            }
        }