Asked  7 Months ago    Answers:  5   Viewed   31 times

Noob webdeveloper here.

I'm trying to download an image from an url on click. But when I use the image url as my href it just redirects to that url instead of downloading. Of course I am using the download attribute. I have tried my own code and also mulitple code blocks from other people. But all of them just redirect. I am using google chrome.

My code:

<a href = "https://autoooo.nl/wp-content/uploads/2018/12/F5144B9C-2B27-4070-828E-2361EBD702EF-400x400.jpeg" download="car" id="downloadQRCodeButtonHref">
   <p>download</p>
</a>

Code I used from someone else 1(accepted answer):

<a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
   <img alt="ImageName" src="/path/to/image">
</a>

Code I used from someone else 2:

 <p> Click the image ! You can download! </p>
<?php
$image =  basename("http://localhost/sc/img/logo.png"); // you can here put the image path dynamically 
//echo $image;
?>
<a download="<?php echo $image; ?>" href="http://localhost/sc/img/logo.png" title="Logo title">
    <img alt="logo" src="http://localhost/sc/img/logo.png">
</a>

Some help will be appreciated. I might just be a big dum dum and overlook something extremely obvious.

 Answers

79

The problem is because you're using a cross-domain URL. From the documentation for the download attribute:

download only works for same-origin URLs, or the blob: and data: schemes.

To fix this you need to host the image on the same domain as the parent site.

Wednesday, March 31, 2021
 
hjalpmig
answered 7 Months ago
43

Check out this page here. It contains a hacky solution that should add the desired functionality

http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari

Wednesday, March 31, 2021
 
ALH
answered 7 Months ago
ALH
91

Alright, I think your problem here is being caused by the FileReader's load event handler, which appends those data URLs to the form, being called after the form is submitted to the server.

You could solve this problem, and do away with the superfluous images variable and submit event handler by adding these items to the form in the click handler for the Add link. You can also use this opportunity to do a little client side validation, preventing duplicate data URLs from being uploaded to the server, and even to add a preview/remove option for the selected images.

Furthermore, you could do away with the Add link by replacing its click handler with a change handler attached to your file input.

Edit (nfplee):

var images = [];

$("#add").click(function() {
    var files = $("#images")[0].files;

    for (var i = 0; i < files.length; i++) {
        var reader = new FileReader();

        reader.onload = (function(file) {
            return function(e) {
                images.push({ name: file.name, file: e.target.result });
            };
        })(files[i]);

        reader.readAsDataURL(files[i]);
    }

    $("#images").val("");
});

var form = $("form");

form.submit(function() {
    for (var i = 0; i < images.length; i++) {
        $("<input>").attr({ type: "hidden",
            name: "images[" + i + "][name]" }).val(images[i].name).appendTo(form);
        $("<input>").attr({ type: "hidden",
            name: "images[" + i + "][file]" }).val(images[i].file).appendTo(form);
    }
});
Saturday, May 29, 2021
 
TecHunter
answered 5 Months ago
45

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character

That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.

What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your &nbsp; strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.

Well anyway, for now you can add one of the following to your document's <head> and see if that makes it look right in the browser:

  • for HTML4: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  • for HTML5: <meta charset="utf-8">

If you've done that, then any remaining problem is ActivePDF's fault.

Tuesday, June 1, 2021
 
leebriggs
answered 5 Months ago
84

Yes, it is by design that the CORS headers have no affect on the download attribute. There are only two browsers that support the download attribute, Firefox and Chrome, and both browsers have a different policy on cross-origin files.

Chrome versions prior to 65 actually did allow the download attribute on cross-origin files, without CORS headers, but Firefox chose not to, citing potential social-engineering attacks.

MDN documents this behavior for Firefox 20 under the download attribute section for the a tag, behavior that has not changed since.

In Firefox 20 this attribute is only honored for links to resources with the same-origin.


This Bugzilla report discussed the security concerns and the possibility of using CORS.

When the user clicks such a link, the user will be prompted if they want to download. It seems very easy for the user to make the mistake of thinking that something on the original website is being downloaded, and not something from bank.com.


Would it be possible to implement it with same-origin and CORS (Access-Control-Allow-Origin) in mind if you are questioning cross origin security? This is very useful feature for web applications (create Blob using JS and let user download it with some meaningful name)

Google was opposed to using CORS for this.


There's also this Bugzilla report, which summarizes their decision from the other bug report.

Also, cross origin downloads are working perfectly in Google Chrome.

Yes, and we think they're adding security bugs by doing that.

The Bugzilla issues don't seem to rule-out the possibility of using CORS for cross-origin download attribute support in the future, but right now using CORS headers does not do anything for the download attribute. It's possible that if other browsers start supporting the attribute, a consensus may yet be reached.

For sake of completeness, there is of course the Content-Disposition header which you can use to force a download from the other domain, but this does not provide the same functionality as the download attribute. It does have better browser support though.

Tuesday, June 8, 2021
 
SuperString
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :