记一次ElementUI上传文件,Current request is not a multipart request与the request was rejected because no multipart boundary was found

1.前端代码(ElementUI)

<template>
  <el-upload
      class="upload-demo"
      ref="upload"
      drag
      action=""
      :limit="1"
      :multiple="true"
      :auto-upload="false"
      :http-request="uploadFileToServer"
      multiple>
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
  </el-upload>
</template>
<script>
  uploadFileToServer(file){
    let formData = new FormData();
    formData.append('file', file.file);
    this.$http.upload('/onlineFile/test',formData).then(e=> {
      console.log(e,"66666");
    })
  },
</script>

2.后端代码(Spirngboot)

@PostMapping("/test")
public void test(@RequestParam("file") MultipartFile file){
    System.out.println(777);
    System.out.println(file);
}
  • 上传代码中不要设置请求头
# 不要设置这个
headers: {
    'Content-Type': 'multipart/form-data'
}

Axios检测到当前请求是formData请求时会删掉Content-Type,如果自己加这个的话会报the request was rejected because no multipart boundary was found错误
原因是:不加的话浏览器自动处理表单请求
请求头是这样的

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryPkQ6gYf4jtuB29ck

加的话

Content-Type: multipart/form-data;

后端加上 @RequestParam("file") 用来接收formData中的值,多个值写多个@RequestParam("file")

请求体中不要加 {} ,new ForData()对象,赋值,将formData直接放到入参对象位置

正确示例

uploadFileToServer(file){
    let formData = new FormData();
    formData.append('file', file.file);
    this.$http.upload('/onlineFile/test',formData).then(e=> {
      console.log(e,"66666");
    })
  },

错误示例

uploadFileToServer(file){
    this.$http.upload('/onlineFile/test',{
    file:file.file
  }).then(e=> {
    console.log(e,"66666");
  })
},
uploadFileToServer(file){
    let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        } 
    }
    this.$http.upload('/onlineFile/test',{
      file:file.file
    },config).then(e=> {
      console.log(e,"66666");
    })
},
uploadFileToServer(file){
    let formData = new FormData();
    formData.append('file', file.file);
    this.$http.upload('/onlineFile/test',{
      file: formData
    }).then(e=> {
      console.log(e,"66666");
    })
},
uploadFileToServer(file){
    let formData = new FormData();
    formData.append('file', file.file);
    this.$http.upload('/onlineFile/test',{
      formData
    }).then(e=> {
      console.log(e,"66666");
    })
},
posted @ 2022-03-10 17:51  Awsly  阅读(1494)  评论(0编辑  收藏  举报