I'm able to successfully download a PDF from an endpoint, but when using the "Share" button on iOS Safari, it tries to share "1 Link and 1 Document". The document is the PDF which is correct, but it's also sharing a link that looks like blob:https://www.example.com/some/url. I'd like to just share the document and not the blob URL.
After making the request, my code looks like this:
const pdfBlob = await response.blob();
const pdfUrl = URL.createObjectURL(pdfBlob);
const a = document.createElement("a");
a.href = pdfUrl;
a.download = saveAsName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(pdfUrl);
How can I just share the document using iOS Safari built-in "Share" button, and not the blob link?
Related
In any browser, if you saw an image, you can right-click on it and click "save as" to download it.
I'm trying to make a button to download an image
The download button should download the image above, the barcode.
I am using react, not sure if this has something to do with the answers.
I read that you can use the <a/> tag with the download attribute, however, I'm on Firefox, and it's redirecting me to a page where the barcode image is hosted, and it's not opening the download window instead:
The code is pretty simple, it look as follows:
<a href='https://barcode.tec-it.com/barcode.ashx?data=${product.barcode}&code=&multiplebarcodes=true&backcolor=%23ffffff&quietzone=10&quietunit=Px&size=Small' download>click me</a>
From the MDN docs:
download only works for same-origin URLs, or the blob: and data:
schemes.
I want to implement this, how can I do it?
I'm not the owner of the server where the image is hosted.
Can we do that in 2023?
The other questions are mixing between local images and images hosted on other servers.
So I thought I could create this thread for people interested only in images on third party servers. - so we are all front-end here, no back-end related stuff.
I think your question refers to this old question.
You need something on the server to send a Content-Disposition header to set the file as an attachment so the browser will not try to handle the file internally.
Please see:
href image link download on click
It only works on the same website, not an external link. Try an image of the same website. Ex: <a href="images/detailed-product.png" download>click</a>
You'll need to proxy the request to avoid CORS issues. As the article states it's better to deploy your own proxy, but you can test with a free one, eg: https://codetabs.com/cors-proxy/cors-proxy.html
StackBlitz updated example:
const downloadButton = document.querySelector('button');
downloadButton.onclick = () => {
console.log('download button clicked');
downloadImage(
'https://api.codetabs.com/v1/proxy?quest=https://barcode.tec-it.com/barcode.ashx?data=${product.barcode}&code=&multiplebarcodes=true&backcolor=%23ffffff&quietzone=10&quietunit=Px&size=Small'
);
};
async function downloadImage(imageSrc) {
try {
const image = await fetch(imageSrc);
const imageBlob = await image.blob();
const imageURL = URL.createObjectURL(imageBlob);
const link = document.createElement('a');
link.href = imageURL;
link.download = 'image.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.log(error);
}
}
<button>Download image</button>
To do that, you can utilize the createObjectURL static method from URL to create download link for the image. Then, we create temporary <a> in a variable to open that link programmatically.
async function downloadImage(imageSrc) {
const image = await fetch(imageSrc)
const imageBlob = await image.blob()
const imageURL = URL.createObjectURL(imageBlob)
const link = document.createElement('a')
link.href = imageURL
link.download = 'myimage.jpg'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
In my website I've a button that whenever user clicks on it downloads him a random image, here is the code to download an image:
const downloadImg = (src) => {
const imgName = src.replace(/^.*[\\\/]/, '');
var a = document.createElement('a');
a.href = src;
a.download = imgName;
a.click();
};
This works completely fine from images that are from open websites, like google.com or Wikipedia commons
However, for images from websites like Pixabay, Pexels, Freepik instead of downloading the Image it opens the image URL in the same tab and gives me 403 forbidden error in the console
I completely understand why this error happens, but what I don't understand is how to fix it? If I right-clicked on the image then hit save image as no error will appear and I will be able to download the image normally, how can I do this with javascript programmatically?
It works using the approach from accepted answer here: Chrome 65 blocks cross-origin <a download>. Client-side workaround to force download? , with a minor change. Instead of using mode "cors" use "no-cors". Apparently there is a cors error with some domains when downloading directly from url.
Updated: It does not work if the server does not allow cros-origin requests. Making the request with "no-cors" will succeed, but the response body will not be available. So this is NOT a solution.
You can use javascript fetch to download the random selected image from url address.
Code:
JS:
<script>
function downloadImage(url, name){
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = name;
document.body.appendChild(a);
a.click();
//window.URL.revokeObjectURL(url);
})
.catch(() => alert('An error sorry'));}</script>
HTML:<button onclick="downloadimage('https://pixabay.com/get/g2cc1f3e1fe58926edc20db6cf67be6dd1614d93b06e934118288e4c57d5228c60c50de32506ac83ffdabc6fe20a6a01b3c7504b82965e6043e9038185180f3ae_1920.jpg', 'download.jpg')" >download</button>
example:
https://viena.lovestoblog.com/bakDownload/bak.php
My web application lets the users "save" a file by downloading it as described below (Source).
However browsers like Firefox in its default setting then tries to open the file and says "Opening filename.json" and not "Saving File". While I understand the reason for this is that the browser tries to immediately open a downloaded file if configured as such, this confuses my users because there are now three different words ("download", "save", "open") for the same operation and they don't know if they chose the wrong one. There is also a load option where users can upload their saved data to load it in the application, adding to the confusion.
Is there any way to tell the browser to stop trying to open the file (which it cannot do anyways, it is a custom format for that web application), or is there any other way to provide more clarity to the users?
export function saveJson(data,fileName)
{
if(a===null)
{
a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
}
const json = JSON.stringify(data);
const blob = new Blob([json], {type: "application/json"});
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
log.debug("JSON File saved: "+fileName);
}
UPDATE:
Creating a Blob from a base64 string in JavaScript
I am trying to implement click a button and download file from its DataURL.
Currently, since the Chrome has restricted the old way such as building <a> link which throws error like:
Not allowed to navigate top frame to data URL: ....
The solution I found is open new window with iframe and set the DataURL as its src
let jpgWindow = window.open("", "_blank")
var html = "<html><body><iframe width='100%' height='100%' src='data:application/jpeg;base64, "+ theDataURL+"'></iframe></body></html>";
jpgWindow.document.write(html)
When I click the button, the download works, but the picture is downloaded with filename "download", there is no way I can specify what file name I want it default to.
Any thought?
Look into window.URL.createObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
const blob = new Blob(['array of data in your file'], {type : 'text/rtf'});
const anchor = document.createElement('a');
anchor.href = window.URL.createObjectURL(blob);
anchor.download = 'the-file-name.txt';
anchor.click();
I have codes below to generate the download link so that users could download the .csv file on my site.
var link = document.createElement("a");
link.id = "csvDwnLink";
window.URL = window.URL || window.webkitURL;
var csv = "\ufeff" + CSV,
blob = new window.Blob([csv], {type: 'text/csv, charset=UTF-8'}),
csvUrl = window.URL.createObjectURL(blob),
filename = 'export.csv';
$("#csvDwnLink").attr({'download': filename, 'href': csvUrl});
$('#csvDwnLink')[0].click();
document.body.removeChild(link);
I hope the user could click the download link with csvUrl to download the cvs file.
It works on chrome. However, when I click the same link using Safari, it will directly show me the content of the csv file in the tab.
How do I solve this problem so that the safari will show the saving file window which user could select the path where they want to save the file instead of showing the content of the cvs file directly when I click the download link?
Hope someone could me some recommendations or alternative methods.
Thanks in advance!
== Updated ==
Find out solutions here
solution 1,
solution 2
The code will be:
var link = document.createElement("a");
link.id = "csvDwnLink";
document.body.appendChild(link);
window.URL = window.URL || window.webkitURL;
var csv = "\ufeff" + CSV,
csvData = 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(csv),
filename = 'filename.csv';
$("#csvDwnLink").attr({'download': filename, 'href': csvData});
$('#csvDwnLink')[0].click();
document.body.removeChild(link);
Safari will download the file for the user, however, the file name will be unknown, probably it's because Safari don't support 'download' attribute yet as raphael mentioned.
I did a quick research - I looks like Safari does not support what you are trying to achieve.
The reason why your solution works in Chrome (and Firefox) is that they support the download attribute - Safari doesn't yet.
Safari 10.1+ supports "download" attribute. It should work now.
https://github.com/eligrey/FileSaver.js/issues/129#issuecomment-275221240