简体   繁体   中英

force download base64 image

To start with JS isn't one of my strengths. I've been trying for the past couple of days to edit this JS function to make it force download base64 image. What the function does, when the download button is clicked, is open a new window with the image on it. The user then has to right click and save the picture. I'm trying to force download the image instead of right click and 'save as'.

The dataurl produce base4 png string (data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQ………)

i tried using as it was suggested in another thread but that didn't work.

All suggestions are welcomed. Thanks.

savePaint: function() {
            var self = this;

            dataURL = self.context.canvas.toDataURL();

            var cntnt = $("<p class='dialogHeader'>Please right click and select 'Save Image As' option. Click here to Return</p>           <img id='PrintImage' src=" + dataURL + ">");
            self.newSavedImage.html(cntnt);

            self.showPopup(self.newSavedImage, self.canvasWidth, self.canvasHeight)
}

Finally! I got it to work. For anyone facing the same problem I found a function here http://danml.com/download.html that will let you force download the base64.

You could specify a different MIME type rather than image/jpeg so the browser doesn't attempt to open the image natively:

data:application/octet-stream;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/...

This will force the file to download, but I noticed in some browser configurations may autosave with a default filename and since the browser doesn't know the real file type it will be up to the user to specify the correct type. Unfortunately the data URI scheme does not allow for a suggested file name.

Check out Using HTML5/Javascript to generate and save a file for more possible solutions. Your best bet, depending on your requirements, might be to go with a Flash-based solution such as Downloadify .

you can try this:
javascript file:

var valuToDecode = document.getElementById("base64-image-string").value;
var linkImg = valuToDecode.concat('" alt="Red dot" download="ganixo-file.png"> click here to download your img </a>');
document.getElementById("codedImg").innerHTML=  '<a href="data:image/jpeg;base64,'.concat(linkImg);

html file:

Image url:<p  id="codedImg"></p>

output:

<p id="codeImg"><a href="data:image/jpeg;base64,iVB..." download="img.png">click here to download your img</a></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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