HTML + JS achieve download pictures to your local

In HTML5, download the new property is <a> notes, download attribute allows us to specify the default name of the browser when downloading files, adding attributes to download <a> connection, when we click on this link, download the property value the name appears in the pop-up box download, download attribute can force the trigger and download operation

1: Pictures can be achieved by <a> download link

<a href="test.jpg" download="图片名字">
     <img src="test.jpg" alt="">
</a>

2: <a> triggered via JS to achieve image to download

<img id="testImg" src="test.jpg" alt="">
<button class="downloadBtn" type="button" οnclick="downloadImg()">下载图片</button>
    function downloadImg () {
         var IMG = document.getElementById ( 'testImg'); // acquired images to be downloaded 
        var URL = img.src;                             // get image address 
        var A = document.createElement ( 'A');           // create an insert of a node the Document 
        var  event =  new new  MouseEvent ( 'click')            // simulate a mouse click click events 
        a.download = 'Image name'                   // set a property value of the node download 
        a.href = url;                                  // will pictures of src assigned to a node href 
        a.dispatchEvent (event)                         // trigger a mouse click event
     }

 

Guess you like

Origin www.cnblogs.com/chao202426/p/11403713.html