Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

javascript - html download attribute redirects to url instead of downloading

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...