Image file format not supported when downloaded from canvas - javascript

When I download image versions of my canvas drawings I am unable to view or access them. My device keeps saying "doesn't support this file format" even though I have the image file labelled as "png" (lowercase too). The file downloads perfectly fine but that's about it. Any idea of what Im doing wrong?, below is the snippet of code. A link to my website too which is responsive [https://webdevcit.com/2018/Sem2/R00125891/Pages/structure/srctr1.html]
Any help would be very much appreciated
Download
function createDownload() {
const downloadURL = document.getElementById('c').toDataURL();
document.getElementById('downloadLink').href = downloadURL;
}

Open you downloaded file with a text editor and you will see it is a HTML Text file and not a PNG.
You are never calling the createDownload() function

Try this!!
let url = canvas.toDataURL();
let a = document.createElement("a");
a.href = url;
a.download = "image.png";
a.click();

Related

Download PDF from url react

I have a publicly accessible url to a PDF in Google Cloud Storage. I want to be able to create a button/link in react which allows users to download this PDF to their own computer. I'm wondering what is the best approach to do this and which libraries would be of help? Is there any documentation on this? Thanks
In order to force download a file, you have a number of options. First, the easiest is using the download attribute of an anchor tag:
PDF
However, this is not supported on IE and a number of other browsers in their earlier versions. But the maximum impact of this is it will open in a new tab which in my opinion is graceful degradation. See the full list of supported versions.
If this is not enough, you have to make some changes server-side. You can configure a server in many ways, but as an example, a .htaccess file can have the following:
<Files *.pdf>
Header set Content-Disposition attachment
</Files>
You can dynamically generate a link or button. Snippet bellow:
var sampleBytes = new Int8Array(4096); // In your case it should be your file
var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "octet/stream"}), // or application/pdf
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());
saveByteArray([sampleBytes], 'example.txt'); // You can define the filename

How can I download a pdf from a url using javascript?

I need to download pdf's from one of our online resources.There is no built in function to batch download.The only way to do it is to navigate to each pdf file, click to open, then click download.
There are several thousand files and this would take a very long time to do.
I got around this in the past using javascript. I gathered all the links to the pdfs, put them in a csv, and had the code loop through each link, download, and move onto the next link.
Unfortunately, I have lost that code and my efforts to recreate it have been unsuccessful.
I have tried everything in this article: How to download PDF automatically using js?
I have tried the code from this article (which I'm pretty sure is what I did before): https://www.convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
This is what I think should work...per the second article I referenced above
function download_file(fileURL, fileName) {
var link = document.createElement('a');
link.href = fileURL;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
}
var fileURL = "link/to/pdf";
var fileName = "test.pdf";
download(fileURL,fileName);
The code above is just to test download one file from a hardcoded URL. If it worked as intended, when the page is loaded, it should download the pdf from the provided url. Instead, it doesn't do anything on load or refresh.
Any suggestions?
Please check
https://stackoverflow.com/a/18983688/6923146
click me
Another one
https://stackoverflow.com/a/45905238/6923146
function download(url, filename) {
fetch(url).then(function(t) {
return t.blob().then((b)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
}
);
});
}
download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,Hello Developer!", "HelloDeveloper.txt");
I hope it helpfull
https://www.convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/
You must add link element to DOM
function download_file(fileURL, fileName) {
var link = document.createElement('a');
link.href = fileURL;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
var fileURL = "https://cdn.sstatic.net/clc/img/jobs/bg-remote-header-sm.png";
var fileName = "test.pdf";
download_file(fileURL, fileName); // fix function name
Link must be in same origin
The download attribute on anchor was ignored because its href URL has a different security origin.

Browser only downloading certain Base64 file types

I have Base64 files that I am trying to have the user download. I do not need these or want these to display in the browser. I need these to download. The data seems to be coming back fine, but only certain types of files are behaving.
I am grabbing down the data in an ajax call and then checking to see if there is any data.
$('button').on('click', function(){
...ajax call
if (data) {
var encode = 'data:image/' + data.dataTypeCode + ';base64,'
var image = encode+data.data;
window.open(image, '_blank');
}
})
This is only opening the word, excel, gif, mpg, tif and pdf files.
This is not opening the png, jpg, mp3 files which I find odd.
You cannot force a user to automatically download a file simply due to the file represented as a data URI or Blob URL being opened in a window. You can offer a file to be downloaded.
const a = document.createElement("a");
a.download = "fileName";
a.href = /* data URI, Blob URL*/;
document.body.appendChild(a);
a.click();

How to show save file dialog in Safari?

I need help. I have an angular app and by using DocRaptor want to generate PDF and save it as file. But I cant trigger the dialog to save file in Safari with any method what I have found on Stack Overflow. Those methods open file in current browser tab and replace site html or open file in new tab. No one cant shows the dialog. Here the examples what I have already tried to use. Environment MacOS - EL Capitan. Safari 9.0.3
Solution #1
var content = 'file content for example';
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
Example jsfiddle. Shows file in current tab. Replaces site. But works in Chrome.
Solution #2
<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Solution #3
<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>
and
$scope.saveJSON = function () {
$scope.toJSON = '';
$scope.toJSON = angular.toJson($scope.data);
var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',window.URL.createObjectURL(blob));
downloadLink.attr('download', 'fileName.json');
downloadLink[0].click();
};
Example Code Snippet. Shows the file content instead of document's html.
Solution #4
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
Example Code Snippet. Replace document with file content in Safari. Works in Chrome.
And similar Solution #5
function download(text, name, type) {
var a = document.createElement("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
Example jsfiddle. Doesnt work at all in Safari. Works in Chrome.
Also I have tried to use libraries like:
FileSaver - It opens file in Safari instead of document. So you should click Cmd+S. Example.
If we use type 'pplication/octet-stream' the name of file will be unknown or there was be an error 'Failed to load resource: Frame load interrupted'. Issue.
Second library Downloadify - doesnt work in Safari at all. Issue.
Angular library nw-fileDialog - instead of save as it shows choose file. Issue.
DocRaptor has own example with jQuery.
Example with angular in jsfiddle. It works in Chrome but in Safari example doesnt work be cause of error with SAMEORIGIN
Refused to display 'https://docraptor.com/docs' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
But if we reproduce it on server and change url on 'https://docraptor.com/docs.pdf' it works and open file in new tab and automatically download the file so you cant choose a folder and after download user see white empty screen tab in browser. If we specify form target="_self" it will work perfect, but console will have an error 'Failed to load resource:'.
I will appreciate any help with this problem.
Thanks.
Regards.
Try using Blob file for this:
// Buffer can be response from XMLHttpRequest/Ajax or your custom Int32 data
function download(buffer, filename) {
var file = new Blob([buffer], {
type: 'application/octet-stream' // Replace your mimeType if known
});
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var converted = e.target.result;
converted.name = filename;
converted.webkitRelativePath = filename;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = converted;
};
fileReader.onerror = function(e) {
throw new Error('Something is wrong with buffer data');
};
fileReader.file = file;
fileReader.readAsDataURL(file);
}
It basically uses filebuffer and download that as an iframe content. Make sure to hook correct mime type so that safari security system will recieved analyse filetype.
Ideally, Solution #2 would be the answer, but the download attribute does not yet have cross-browser support.
So you have to use a <form> to create the download. As you noted, DocRaptor's jQuery example uses this technique.
The SAMEORIGIN error is actually because JSFiddle is running the code in an iFrame with their origin settings. If you run this straight from your Angular application, you shouldn't have any problems.

Format of image downloaded in client-side

I am downloading images in html page using javascript. This works in latest firefox and chrome browsers.
What I would like to know is the format in which the image will be saved? Though, we can give formats in file name like image.png, will it be saved in png format?
The source of the image is SVG graphics, so this image is completely generated and downloaded in client-side. I am using the following code for downloading:
var canvas = document.getElementById('canvas2');
svg = $("#container").html();
canvg(canvas, svg);
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var downloadLink = document.createElement("a");
downloadLink.href = image;
downloadLink.download = "imge.png";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
Here image is the javascript variable in which the image is stored.
It will be saved in the format of the original image. Browsers do not do image conversion.

Categories

Resources