单文件上传
前端部分:
<template>
<br>
<a-from label="上传文件">
<a-input type="file"></a-input>
<a-button @click="upload" type="danger">上传</a-button>
</a-from>
</template>
<script>
export default {
data() {
return {
headers: {
authorization: 'authorization-text',
},
};
},
methods: {
upload() {
const formData = new FormData();
formData.append("file",document.querySelector('input[type=file]').files[0])
// 因为不是以json的形式提交,所以无需使用qs转换
this.$axios.post('/postfile',formData).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
}
},
};
</script>
后端:
func PostFile(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message" : err.Error(),
})
return
}
log.Println(file.Filename)
dst := fmt.Sprintf("uploadfile\\%s", file.Filename)
c.SaveUploadedFile(file, dst)
c.JSON(http.StatusOK, gin.H{
"message" : fmt.Sprintf("'%s' uploaded!", file.Filename),
})
}
多文件上传
前端:
<template>
<br />
<a-from label="多文件上传">
<a-upload > </a-upload>
<input type="file" class="files" multiple="multiple">
<a-button @click="upload" type="danger">上传</a-button>
</a-from>
</template>
<script>
export default {
data() {
return {
headers: {
authorization: "authorization-text",
},
};
},
methods: {
upload() {
const formData = new FormData();
const file = document.getElementsByClassName("files")[0].files;
// console.log("上传的文件数量:" + file.length);
for (let i = 0; i < file.length; i++) {
formData.append("file", file[i]);
}
this.$axios
.post("/postfiles", formData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
},
},
};
</script>
后端:
func PostFiles(c *gin.Context) {
form, _ := c.MultipartForm()
files := form.File["file"]
for _, file := range files {
log.Println(file.Filename)
dst := fmt.Sprintf("uploadfile\\%s", file.Filename)
c.SaveUploadedFile(file, dst)
}
c.JSON(http.StatusOK, gin.H{
"message" : fmt.Sprintf("%d files uploaded!", len(files)),
})
}
参考文章:http://blog.ncmem.com/wordpress/2023/11/09/vue%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0/
欢迎入群一起讨论
标签:files,文件,vue,log,formData,Filename,file,上传 From: https://www.cnblogs.com/songsu/p/17819339.html