2016-11-25 77 views
0

我已经使用下面的代码下载图像与给定的名称。但是,这似乎并没有下载图像与它自己的图像扩展。图像不能下载,它具有自己的扩展名

这里是HTML

<a id="btnDownload" href="www.mywebsite.com/images/myimage.jpg" onClick="downloadImage(www.mywebsite.com/images/myimage.jpg);" >download</a> 

和代码

function downloadImage(sUrl){  
    window.URL = window.URL || window.webkitURL; 
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', sUrl, true); 
    xhr.responseType = 'blob'; 
    xhr.onload = function(e) { 
     var res = xhr.response; 
     var blob = new Blob([res], {type:'image'}); 
     url = window.URL.createObjectURL(blob); 
     var a = document.createElement("a"); 
     a.href = url; 
     a.download = "My image name"; 
     document.body.appendChild(a); 
     a.click(); 
    }; 
    xhr.send(); 
} 

我想是我想与 “我的形象的名字。” “扩展” 下载图像。这里的图像确实有像jpeg,png,gif这样的替代扩展。 但是这段代码总是下载没有扩展名的文件。这里有什么变化?

+0

您可以只添加'在'一个download'属性'标签。 –

+0

我不确定,但是'{type:'image'}'部分应该指向完整的MIME类型标识符,例如示例的'image/jpeg'。 –

+0

首先参数应该是一个字符串或更简单的this.href。 – Lain

回答

0

为了让你的榜样扩展,你可以这样做:

a.download = "My image Name." + window.URL.split('.').pop(); 

但我会用不同的数据属性的工作:

<html> 
    <!-- 
     You can put the href and the name you want to see in different data attributes. 
     Also one can add IE support. 
    --> 

    <head> 
     <script> 
      //e:=<a [data-name] [data-href]> 
      function downloadMe(e){ 
       var tF = e.getAttribute('data-name'); 
       var tURL = e.getAttribute('data-href') 

       var tR = new XMLHttpRequest(); 
       tR.open('GET', tURL, true); 
       tR.responseType = 'blob'; 

       tR.onload = function(e){ 
        var tB = this.response; 

        if(window.top.navigator.msSaveOrOpenBlob){ 
         //Store Blob in IE 
         window.top.navigator.msSaveOrOpenBlob(tB, tF) 
        } 
        else{ 
         //Store Blob in others 
         var tA = document.body.appendChild(document.createElement('a')); 
         tA.href = URL.createObjectURL(tB); 
         tA.download = tF; 
         tA.style.display = 'none'; 
         tA.click(); 
         tA.parentNode.removeChild(tA) 
        } 
       }; 

       tR.send(); 

       return false 
      } 
     </script> 
    </head> 

    <body> 
     <a href = '#' data-href = 'A.png' data-name = 'My Name.png' onclick = 'return downloadMe(this)'>download</a> 
    </body> 
</html> 
+0

为您的方式添加了修复程序:) – Lain

相关问题