使用gin框架上传文件,仅个人想法。
后端接口:
func uploadFile(context *gin.Context) {
result := &model.BaseResult{}
file, header, err := context.Request.FormFile("file")
if err == nil {
filename := header.Filename
out, err := os.Create("static/res/uploadFile/excel/" + filename)
if err == nil {
defer out.Close()
_, err = io.Copy(out, file)
if err == nil {
log.Println("上传表格成功")
res :=map[string]interface{}{
"filePath":"/res/uploadFile/excel/" + filename,
"fileName": filename,
}
result.Code =0
result.Data = res
result.Msg ="上传表格成功"
}else {
result.Code = -3
result.Msg ="复制文件出错"
}
}else {
result.Code = -2
result.Msg ="创建文件出错"
}
}else {
result.Code = -1
result.Msg ="接收表格出错"
}
context.JSON(http.StatusOK, result)
}
前端ajax请求
$(document).on('change', '.uploadExcel', function () {
var formData =new FormData();
var f =$('.uploadExcel')[0].files[0]
if (f !==undefined) {
formData.append('file', f);
$.ajax({
url:"/uploadFile",
type:"POST",
data: formData,
contentType:false,
processData:false,
dataType:"json",
mimeType:"multipart/form-data",
success:function (res) {
console.log(res.data)
if (res.code ===0) {
alert("上传文件成功")
}else {
alert("上传文件失败")
}
},
error:function (err) {
console.log(err)
}
})
}
});
前端也可使用form表单提交文件