vue+gin上传文件
前端
html
<form action="" method="post" enctype="multipart/form-data"> <input id="fileUpload" type="file" name="upload"> <input type="button" @click="submitfile"> </form>
js
submitfile() { var formData = new FormData() var formData = new window.FormData() formData.append("f1",$("#fileUpload")[0].files[0]); console.log(formData) //开始Ajax请求 var options = { // 设置axios的参数 url: this.baseUrl+'/upload', data: formData, method: 'post', headers: { 'Content-Type': 'multipart/form-data' } } axios(options).then((res) => { console.log(res) }) },
后端:
func UploadFile(c *gin.Context){ file, err := c.FormFile("f1") if err != nil { log.Println("get file failed!",err.Error()) c.JSON(http.StatusInternalServerError, gin.H{ "message": err.Error(), }) return } log.Println(file.Filename) dst := fmt.Sprintf("F:/go/demo/employ/files/%s", file.Filename) // 上传文件到指定的目录 c.SaveUploadedFile(file, dst) err = CreateResume(file.Filename) if err!=nil{ c.JSON(http.StatusOK, gin.H{ "message": fmt.Sprintf("failed"), }) return } resume:=GetResumeByName(file.Filename) c.JSON(http.StatusOK, gin.H{ "message": "success", "id":resume.Id, }) }