Home > Blockchain >  Vue - reload data after href download starts
Vue - reload data after href download starts

Time:01-20

I am making a simple window.location.href call to start a file download. After that, I call a method to reload a table.

window.location.href = url;
this.getFileListing();

But the reload is too fast, because the href creates a database record.

Adding a 1 second timeout fixes it:

window.location.href = url;
setTimeout(() => {
    this.getFileListing();
}, 1000);

...but that's sloppy. How do I wait for the download to start (thus the database record will exist) before I call the reload?

*Note: the location of the window is not changing. I am just using windows.location.href to call a local route, which starts downloading a file. Therefore, I do not believe popstate or hashchange will work.

CodePudding user response:

instead of launch download with window.location.href for vue you can use axios to download a file and use then method on promise to launch the needed method

 axios({
   url: url,
   method: 'GET',
   responseType: 'blob'
 .then(response => (this.getFileListing()))

If you are using jQuery you can try something equivalent with jquery get https://api.jquery.com/jquery.get/

var instance = this;
$.get("fileToDownload", function() {
    //code when download is launch
}).done(function() {
    instance.getFileListing();
})

CodePudding user response:

My solution: to use axios and a LOT of code to grab the response, and pass it to the browser. I had to parse out the original filename. Not sure if it was worth it. I actually put the functions in a mixin so I could add it easily to other components.

downloadToBrowser(url, successCallback) {
  const that = this;
  axios({
    method: 'GET',
    url: url,
    responseType: 'blob'
  })
  .then( function(response) {
    that.startDownload(response);
    successCallback();
  });
},
startDownload(response) {
  var filename = response.headers['content-disposition'].split('=')[1];
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
},

Then call the method, passing in the url and callback:

this.downloadToBrowser(url, this.getFileListing);
  •  Tags:  
  • Related