Faridah Ainun Jariyah
Faridah Ainun Jariyah

Reputation: 13

Force Download using Vue

I tried the code and it worked only for files with the format doc and pptx. If I want to download images, this code instead displays a new tab on Google.

can anyone help? Or have a code that can help download problems. I want a function that can download all types of files.

<a
   class="btn btn-success btn-xs"
   :href="'http://api.smartsport.site/'+props.row.url"
   target="_self"
>Download</a>

Upvotes: 0

Views: 2033

Answers (2)

user2638618
user2638618

Reputation:

The download attribute tells the browser that you want it to download the file, but it will not always work. Internet Explorer does not recognize it, and Chrome and Firefox will ignore it for cross-origin requests (CanIUse). Since you're linking to resources from another site there is no way to reliably make the a tag download, even in browsers that support the attribute.

I'm not sure if this would work differently, but to avoid directly linking to the API you could try a Blob download from the API instead. There is an issue on Github that addresses how to do this. I slightly modified one of the answers to make a method you could try using.

download: function(url) {
    let response = await Vue.http.get("http://api.smartsport.site/" + url, {responseType: 'arraybuffer'});
    let blob = new Blob([response.data], {type:response.headers.get('content-type')});
    let link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = this.name;
    link.click();
}

Source: https://github.com/pagekit/vue-resource/issues/285#issuecomment-359112845

Upvotes: 1

ittus
ittus

Reputation: 22403

You can use download attribute

<a
   class="btn btn-success btn-xs"
   :href="'http://api.smartsport.site/'+props.row.url"
   download
>Download</a>

You might want to use FileSaver which support other features.

Upvotes: 0

Related Questions