前端基本用法:点击查看
实现代码:
const afterRead = (file) => {
console.log(file);
//set content-type to multipart/form-data
const formData = new FormData();
formData.append("file", file.file);
request.POST("/api/v1/users/upload", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((res) => {
console.log(res);
});
};
后端代码:
func (h *usersHandler) Upload(c *gin.Context) {
// 上传单张图片
file, err := c.FormFile("file")
if err != nil {
logger.Error("FormFile error", logger.Err(err), middleware.GCtxRequestIDField(c))
response.Error(c, ecode.InternalServerError)
return
}
filename := file.Filename
// 保存文件到static/pictures
err = c.SaveUploadedFile(file, "./static/pictures/"+filename)
if err != nil {
logger.Error("SaveUploadedFile error", logger.Err(err), middleware.GCtxRequestIDField(c))
response.Error(c, ecode.InternalServerError)
return
}
response.Success(c, gin.H{"message": "upload success"})
}