Question

My question may seem weird as I am not sure how to phrase it!!! The problem is that I have written a function in js

function onSavePNG(url){
    var save =  document.createElement('a');
    console.log('url in save function'+url);
    save.href = url;
    console.log('save.href'+save.href);
    save.target = '_blank';
    save.download = 'Slide no '+(i+1)+'.png' || 'unknown';
    var event = document.createEvent('Event');
    event.initEvent('click', true, true);
    save.dispatchEvent(event);
    (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

The argument 'url' is a dataURL from a canvas, the function is supposed to save the image to the disk. save.href is not holding the actual dataURL, It has changed to

'http://localhost:3000/data:image/png;base64.......'

and I am getting no file. What should I do so that this

'http://localhost:3000/' 

does not become the part of dataURL assigned to save.href?

Was it helpful?

Solution

I solved my problem by removing the single quotes appearing at the beginning and end of the dataURL

function onSavePNG(url){
    var save = document.createElement('a');
    console.log(url[0]+'  '+url[url.length-1]);
    url = url.slice(1);
    url = url.substring(0,url.length-1);
    console.log(url[0]+'  '+url[url.length-1]);
    save.href = url;
    save.target = '_blank';
    save.download = 'Image.png' || 'unknown';
    var event = document.createEvent('Event');
    event.initEvent('click', true, true);
    save.dispatchEvent(event);
    (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

It's working now :)

OTHER TIPS

since save is an <a> element, just using save.pathname (just the path) instead of save.href (whole URL) in the last line of your code should do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top