/minip.jpg

技术博客分享

2024-04-28-采用from-data传参后端获取不到参数问题

/weixin_miniapp.png

采用from-data传参后端获取不到参数问题

问题的起因是在项目中编写的一个上传文件的接口中,前端采用axios+elementplus的上传组件,后端采用go

代码如下

   <el-upload
              ref="upload"
              name="file"
              :http-request="handleRequest"
              :limit="1"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <el-button class="ml-3" type="success" @click="submitUpload">
                上传
              </el-button>
            </el-upload>
​
function handleRequest (e) {
      const fd = new FileReader()
  fd.readAsDataURL(e.file)
  // 将文件转化为base64格式传入后端
  fd.onload = () => {
    axios .post('http://127.0.0.1:8989/upload', {
        imgUrl: fd.result,
      }) .then((res) => {
        imageUrl.value = res.data.data
      })
  }
  // 上传blob格式
  axios.post('http://127.0.0.1:8989/upload', {
      imgUrl: URL.createObjectURL(e.file),
    }).then((res) => {
      imageUrl.value = res.data.data
    }) 
  }
func UploadFile(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Only POST requests are allowed.", http.StatusMethodNotAllowed)
        return
    }
    // 解析多媒体表单
    err := r.ParseMultipartForm(10 << 20) // 最大文件大小为10MB
    if err != nil {
        http.Error(w, "Failed to parse multipart form.", http.StatusInternalServerError)
        return
    }
    // 获取表单中的文件
    file, _, err := r.FormFile("file")
    if err != nil {
        http.Error(w, "Failed to retrieve file from form.", http.StatusInternalServerError)
        return
    }
    defer file.Close()
    //创建新文件保存文件
    dst, err := os.Create("aliyunOSS/happy001.png")
    if err != nil {
        http.Error(w, "Failed to create destination file.", http.StatusInternalServerError)
        return
    }
    defer dst.Close()
    // 将上传的图片数据复制到文件中
    _, err = io.Copy(dst, file)
    if err != nil {
        http.Error(w, "Failed to copy file contents.", http.StatusInternalServerError)
        return
    }
    // 告知客户端图片已成功上传
    fmt.Fprintf(w, "File successfully uploaded as %s", "happy.png")
}
​

开始用apifox测试的时侯一切正常,后面前端测试一直报错Failed to retrieve file from form.没有这个参数,再次用apifox测试也能上传,很奇怪.