'How to force browser to download file using vue.js?
I'd like to let users to download images by clicking on a download icon:
The image file is already fetched from the server and displayed:
<img :src="currentMediaUrl">
The button is intended to force the browser to download the image above:
<i @click="downloadMedia(currentMediaUrl)" class="fa fa-download"> </i>
Here is what I've tried:
downloadMedia(media) {
let uriContent = "data:application/octet-stream," + encodeURIComponent(media);
window.open(uriContent, 'neuesDokument');
},
But it downloads a file containing the media URI instead of the very file.
How can I fix it?
Solution 1:[1]
That's a normal behavior, considering that you're encoding the URL itself instead of its content.
You can get desired result another way:
<a :href="currentMediaUrl" download><i class="fa fa-download"></i></a>
Solution 2:[2]
You would do this the same way you would in normal html5, namely by using a link element, setting the download attribute and... voila!
<a href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAnElEQVR42u3RAQ0AAAgDIE1u9FvDOahAJzXFGS1ECEKEIEQIQoQgRIgQIQgRghAhCBGCECEIQYgQhAhBiBCECEEIQoQgRAhChCBECEIQIgQhQhAiBCFCEIIQIQgRghAhCBGCEIQIQYgQhAhBiBCEIEQIQoQgRAhChCAEIUIQIgQhQhAiBCEIEYIQIQgRghAhCBEiRAhChCBECEK+W0L3+TnU7375AAAAAElFTkSuQmCC"
download="myImage.png"
target="_blank"
>
Download
</a>
In your case it would be:
<a :href="currentMediaUrl" download="myPrettyFileName.png">
<i class="fa fa-download" aria-hidden="true"></i>
</a>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
