Forcing a Download with Vue.js

After testing the code, it appears to only work for files in the doc and pptx formats. When attempting to download images, the code causes a new tab to open on Google instead.

Is there anyone who can provide assistance or share a different piece of code that solves this problem? I am looking for a function that is capable of downloading all types of files.

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

Answer №1

Utilizing the download attribute signals to the browser that a file should be downloaded, but its effectiveness is not universal. Internet Explorer does not acknowledge it, and Chrome and Firefox may overlook it for cross-origin requests (CanIUse). Given that you are linking to resources from an external site, ensuring the a tag enables downloads reliably proves challenging, even on browsers supporting this attribute.

If direct linking to the API poses concerns, consider attempting a Blob download directly from the API. A Github issue discussion outlines how this can be achieved, with a modified approach for implementation provided below:

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();
}

Find more details at: https://github.com/pagekit/vue-resource/issues/285#issuecomment-359112845

Answer №2

The download attribute can be utilized for downloading files easily.

<a
   class="btn btn-primary btn-sm"
   :href="'http://api.mywebsite.com/'+props.row.file"
   download
>Download</a>

If you require additional functionalities, consider using FileSaver.js.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hello there, I'm attempting to make the links in the description clickable. I'm a bit unsure about how to achieve this, could someone please lend me a hand and have a look?

click here to see the image JavaScript is proving to be a bit challenging for me as a beginner. Can someone help me set it up properly? I know it's probably simple, but I'm struggling to figure it out. Thank you so much in advance! ...

Steps for assigning an id to an element using Selenium

When using Selenium, you have the ability to access the underlying DOM of the browser being manipulated through IWebElement instances. For example: IWebElement domWrapper = driver.FindElement(By.Name("q")); But what if you have the "domWrapper" instance ...

Angular HotTowel with Immediately-Invoked Function Expression (IIFE)

As I delve into the realm of HotTowel templates for AngularJS, a myriad of "why" questions flood my mind. While I have managed to answer some of them, one still remains elusive. Specifically, I am puzzled by the use of "Immediately-Invoked Function Express ...

Your program has encountered a crash and is currently on standby for any file modifications

=> MongoDB initialization in progress. W20210705-14:19:04.925(7)? (STDERR) /Users/alexio/.meteor/packages/promise/.0.11.2.cvynt8.js8ni++os+web.browser+web.browser.legacy+web.cordova/npm/node_modules/meteor-promise/promise_serv ...

Ensure to verify within the ngOnInit function whether the checkbox has been selected

Hi everyone, I'm currently facing a situation where I have a list of checkboxes on one screen. When I select some checkboxes, they move to another screen and remain selected there. However, the issue is that when I try to use a button on the second sc ...

Submitting data via AJAX using the method parameter

I have a specific ajax form that requires serialization and the manual setting of the _method for the data form. This is how I am currently handling it. $.ajax({ url: http://someposturl.com/object, type: 'POST', ...

Exploring ways to utilize removeEventListener in React Native

Can someone assist me with converting this code to React? I am new to using React and struggling with the implementation. Thank you in advance! <progress id="bar" value="0" max="110"></progress> <button onClick={i ...

Transition from Vue2 to Vue3: Embrace the evolution

Could someone assist me in converting this vue wrapper to be compatible with Vue3? I have attempted it myself, but the components that I try to render using my buildApp method are not appearing. Is there an alternative for the Vue object imported from vu ...

Authorization setup encountered an issue: an unexpected character was found at the beginning of the JSON data on line 1, column

I'm currently in the process of setting up a login page for users on my website, using mongoose, express, bcrypt, and nodejs. However, I am encountering an issue when trying to input the username and password. The error message that I receive is as fo ...

Complete a submission using an anchor (<a>) tag containing a specified value in ASP.Net MVC by utilizing Html.BeginForm

I am currently using Html.BeginFrom to generate a form tag and submit a request for external login providers. The HttpPost action in Account Controller // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public Acti ...

Limiting the amount of tasks in order to manage memory consumption

My web application loads entire files into memory on each request and performs asynchronous tasks with their contents. I'm concerned about running out of memory, so I want to restrict the number of files processed simultaneously. If file sizes were kn ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

What method works most effectively for breaking down a large (nested) object?

My objective involves destructuring a large nested object and assigning its properties to variables. Currently, I am doing it this way: const { name, country, sunrise, sunset, timezone } = this.state.weather?.city || {}; const { temp, feels_like } ...

Having trouble with transferring information from JQuery to PHP

Currently, I'm working on transmitting data from jQuery to PHP. Here's an excerpt of what I've done: var jsonArray = JSON.stringify(dataArray); $.ajax({ type: "POST", url: "addcar_details.php", ...

Creating a function with a flexible number of parameters assigned to a variable:

When setting up a Socket.IO client, I have multiple methods structured like the following: myobject.prototype.A = function (callback) { this.foo('a', null, callback); } myobject.prototype.B = function (bar, callback) { this.foo('b&a ...

I found that using Enzyme's shallow().text() in React Native did not perform as I had anticipated

I'm currently exploring React Native testing using enzyme and react-native-mock. Excluded from the discussion: A customized compiler for mocha to utilize Babel features. Here is the code snippet: Block.jsx: import React from 'react'; imp ...

The API call is successful, however the data is empty when returned in the callback function

Utilizing npm Express and Request modules, I am retrieving movie information through an API: var express = require("express"); var app = express(); var request = require("request"); app.get("/results", function(req, res){ console.log(getBody("http:// ...

Having trouble activating the onclick event on a radio button

In my testing framework, I have implemented a keyword-based approach using Selenium 3.x and Java. One of the web elements I am working with is: <input id="radiobutton" name="webserviceBarFlg" onclick="setReadOnly(this)" class="foo-input-radio-margin fo ...

Where should data processing be conducted: in the service or controller layer?

Here's a question regarding the best practices for organizing code. I'm fetching data from an API using $resource and I need to manipulate it before displaying it on the view. My dilemma is at which stage should I process the data? My current b ...

Updating the document array within a Mongo database using an Angular controller

I'm currently facing a challenge when it comes to inserting a new JSON object into an array of JSON objects in MongoDB from my Angular Controller. To simplify, let's consider this schema: var ItemSchema = new mongoose.Schema({ id: Number, ...