简体   繁体   English

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

[英]Convert Blob to File and preview on browser (not download)

I am getting a Blob content from webservice callout and requirement is to display the file in browser. 我从webservice callout获取Blob内容,并且要求是在浏览器中显示该文件。

What I have: 是)我有的:

  • Blob file (fileBlob) Blob文件(fileBlob)

Above blob parameter I get as response and sending same back to javascript method in "callback". 上面的blob参数我得到了响应并将其发送回“回调”中的javascript方法。 I am trying to convert the blob to respective file format and view on browser (I dont want to download unless enduser wants so). 我试图将blob转换为相应的文件格式并在浏览器上查看(我不想下载,除非终端用户想要这样)。

I tried below: 我试过以下:

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

Update 更新 在此输入图像描述

Update 2 (after treating response as base64) 更新2 (将响应视为base64) 在此输入图像描述

Make use of iframe to display pdf file, the function would look like this with blob response and file name. 利用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>')

            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM