Reputation: 387
I need to upload a file to a google cloud bucket using vuejs and axios.
I've got it working through the following html form:
<form action="https://storage.googleapis.com/some-bucket"
method="post" enctype="multipart/form-data">
<input type="hidden" name="key" value="${filename}" />
<input type="hidden" name="success_action_status" value="201" />
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
I can't get it to work with axios.
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>File
<input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
</label>
<button v-on:click="onSubmit()">Submit</button>
</div>
</div>
Methods
methods: {
onSubmit() {
let formData = new FormData();
formData.append('file', this.file);
let response = axios.post('https://storage.googleapis.com/some-bucket', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
})
console.log(response)
}
handleFileUpload() {
this.file = this.$refs.file.files[0];
},
}
How do I get this to work using axios?
Upvotes: 4
Views: 1726
Reputation: 1312
You need to use the following function to put a file in Google Cloud Storage using axios (there is also a xhr example) :
export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => {
let resultState = { state: '', data: {} };
console.log(signedurl)
/*
const xhr = new XMLHttpRequest();
xhr.open("PUT", signedurl);
xhr.setRequestHeader('Content-Type', "application/octet-stream");
xhr.send(file);
*/
let config = {
headers: {
'Content-Type': 'application/octet-stream',
},
};
await axios.put(signedurl, file, config).then(function (response) {
resultState.state = 'success';
}).catch(function (error) {
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
console.log(error)
})
return resultState;
}
Upvotes: 0
Reputation: 1920
@deanjaymay I notice in you're working html form you're using http method POST but in Vue with axios you are using method PUT. Could it be as simple as changing the axios version to axios.post?
Side note, your axios calls will always return a response, be it a successful one or an error. You should add a,
let response = axios.post ...
and then log the response to give you some clues
console.log("response:", response)
UPDATE @deanjaymay I think the problem may be to do with the endpoint you're using. Can you try changing your header to "multipart/related" and see if that works? From what I read, the google cloud storage endpoint IS for multipart uploads, but not form based multipart uploads. A little confusing but from reading their docs that's what I'd probably try?
Upvotes: 1