Vuetify File Uploads
I'm trying to upload a file in Vue.js using vuetify and then save the uploaded file in my data object. HTML: In m
Solution 1:
This following code works fine for me. I've used axois for HTTPClient you might choose anything
<div id="app">
<v-btncolor="blue-grey"class="black--text" @click.native="openFileDialog">
Upload
<v-iconrightdark> cloud_upload</v-icon></v-btn><inputtype="file"id="file-upload"style="display:none" @change="onFileChange"></div>Vue.use(Vuetify);
var vm = newVue({
el: "#app",
data: {
formData: newFormData(),
},
methods: {
openFileDialog() {
document.getElementById('file-upload').click();
},
onFileChange(e) {
var self = this;
var files = e.target.files || e.dataTransfer.files;
if(files.length > 0){
for(var i = 0; i< files.length; i++){
self.formData.append("file", files[i], files[i].name);
}
}
},
uploadFile() {
var self = this;
axios.post('URL', self.formData).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
},
},
});
Solution 2:
The following code works for me. Front end: vue + vuetifyjs + typescript
<template><v-container><v-file-inputmultiplelabel="File input" @change="selectFile"></v-file-input><v-btn @click="upload">Upload</v-btn></v-container></template><scriptlang="ts">import { Component, Vue } from'vue-property-decorator'importAxiosfrom'axios'
@Component({
components: {}
})
exportdefaultclassLogDecodeextendsVue {
currentFile = ''
selectFile (file: any): void {
this.currentFile = file[0]
}
upload (): void {
const formData = newFormData()
formData.append('file', this.currentFile)
Axios.post('/upload', formData)
.then(response => {
console.log({ response })
}).catch(error => {
console.log({ error })
})
}
}
</script>
Server side: Golang + Gin
funcuploadFile(c *gin.Context) {
log.Println("upload...")
file, header, err := c.Request.FormFile("file")
if err != nil {
fmt.Println(err)
c.String(http.StatusBadRequest, "Bad request")
return
}
filename := header.Filename
fmt.Println(file, err, filename)
out, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
log.Fatal(err)
}
c.String(http.StatusCreated, "upload successful \n")
}
Post a Comment for "Vuetify File Uploads"