Click the button in H5 to download the picture


In the development of uni app project, one requirement is to click the button to download multiple pictures, and the picture path is returned from the background. (saveimagetophotosalbum in uni app is not available) ——————- the following code is obtained by referring to other people’s methods and my own personal practice

Method 1:


var oA = document.createElement("a");
           oA. download = index||'photo'; //  Set the file name to download. The default is' download '
           oA. Href = URL -------------------------------------- here is your picture address

This method can be downloaded on both PC and mobile browser, and pictures can be saved in photo album in mobile browser (QQ browser) to test mobile phone (Apple 13)

However, when saving multiple pictures, you can only save the middle one, both PC and browser

Method 2:

let image = new Image();
   //Solve the problem of cross domain canvas pollution
     image.setAttribute("crossOrigin", "anonymous");
     image.onload = function() {
     let canvas = document.createElement("canvas");
     canvas.width = image.width;
     canvas.height = image.height;
     let context = canvas.getContext("2d");
     context.drawImage(image, 0, 0, image.width, image.height);
     let img = canvas. toDataURL("image/png"); // Get the base64 encoded data of the picture
     let a = document. createElement("a"); //  Generate an a element
     let event = new MouseEvent("click"); //  Create a click event = name|| "photo"; //  Set the picture name, ------------- the name of the picture you passed
     a.href = img; //  Set the generated URL to the a.href attribute
     a.dispatchEvent(event); //  Click event triggering a
   image. src = url;---------------- Your picture address

This method can be downloaded on PC and mobile browser. Pictures can be saved in photo album in mobile browser (QQ browser) — test mobile phone (Apple 13) — cross domain problems are reported occasionally

Single picture is OK, and multiple pictures sometimes report cross domain

Method 3

    var iframe = document.createElement('iframe');
    iframe.src =url = "display:none";

This method can be downloaded on the PC, and there is no response when clicking in the mobile browser (QQ browser). It can be downloaded to the browser in Apple’s Safari browser to test the mobile phone (Apple 13)

Single or multiple copies can be downloaded


Recommended Today

Vue2 technology finishing 3 – Advanced chapter – update completed

3. Advanced chapter preface Links to basic chapters: Link to component development: 3.1. Custom events of components 3.1.1. Binding custom events There are two implementation methods here: one is to use v-on with vuecomponent$ Emit implementation [PS: this method is a little similar to passing from child to parent]; The other is to use ref […]