Skip to content

Instantly share code, notes, and snippets.

@11joselu
Last active March 7, 2018 17:39
Show Gist options
  • Save 11joselu/2096717e444849b597a5a2e3f2080eaf to your computer and use it in GitHub Desktop.
Save 11joselu/2096717e444849b597a5a2e3f2080eaf to your computer and use it in GitHub Desktop.
Donwload File - Vue.js 2.x
export function getFile(response) {
var result = document.createElement('a');
var contentDisposition = response.headers.get('Content-Disposition') || '';
var filename = contentDisposition.split('filename=')[1];
filename = filename.replace(/"/g,"")
return response.blob()
.then(function(data) {
result.href = window.URL.createObjectURL(data);
result.target = '_self';
result.download = filename;
return result;
})
}
import * as fileUtil from '../fileUtils';
this.$http.post('/generate', data)
.then(fileUtil.getZIPData)
.then((link) => {
link.click();
})
.catch((err) => {
console.log(err)
})
@Pokom
Copy link

Pokom commented Jun 7, 2017

Hey @11joselu, is this still relevant, or have you found a better solution?

For now I will use this, so I graciously thank you for creating this gist!

@gurpal2000
Copy link

gurpal2000 commented Aug 25, 2017

I was unable to get a lot of snippets that look like this working with vue-resource - unless I explicitly specified the responseType as blob.

this.$http.post('/api/download', object, {
  responseType: 'blob'
})

@fgcui1204
Copy link

fgcui1204 commented Sep 5, 2017

hello, @11joselu I use this code in my project, but it doesn't work.
there is an error:

TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
    at eval (fileUtils.js?b651:9)
    at <anonymous>

does anyone know the reason? need you guys help. thanks

@11joselu
Copy link
Author

11joselu commented Jan 18, 2018

@Pokom still use the same code, with package lock version into vue-resource :(

@fgcui1204 I don't knwo if you still having this issue, but maybe this can help you:

https://stackoverflow.com/questions/27120757/failed-to-execute-createobjecturl-on-url

See: https://developer.mozilla.org/es/docs/Web/API/URL/createObjectURL

@torbentschechne
Copy link

torbentschechne commented Mar 7, 2018

@11joselu I do not understand what needs to be the result from your api call? The file path?
And why do you use getZIPData when getZIPData is not mentioned in fileUtils.js?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment