MissingServletRequestPartException:Required request part ‘file‘ is not present上传文件报错

前端使用的upload:

<el-upload
        action=""
        :http-request="uploadPost"
        :show-file-list="false"
        :on-change="onChange"
        list-type="picture">
    <img :src="dialogImageUrl" >
</el-upload>
onChange(file,fileList){
                this.dialogImageUrl = file.url;
                this.file = file;
                console.log(file);
            },
            uploadPost(){
                let formData = new FormData();
                formData.append('file',this.file.raw);
                // 文件上传必须设置http请求头信息
                request.post("/api/main/uploadPicture",formData,{
                    headers:{'Content-Type':'multipart/form-data;charset=utf-8'}
                }).then(res => {
                    if(res.code == '0'){
                        this.$message.success("上传成功!");
                    }else{
                        this.$message.error(res.code+' 上传失败!'+res.msg);
                    }
                },error => {
                    console.log('253: 错误! '+error);
                })
            },

这里最重要的是formData.append('file',this.file.raw);取得是this.file.raw

然后记得设置http请求头{
                    headers:{'Content-Type':'multipart/form-data;charset=utf-8'}
                }

后端:

@PostMapping("/uploadPicture")
    public Result<?> uploadPicture(@RequestBody MultipartFile file){
       try{
           if(!file.isEmpty()){
               System.out.println("上传头像");
               String imgPath = "C:/Users/Administrator/Desktop/img";
               File f = new File(imgPath+new Date().getTime()+file.getOriginalFilename());
               byte[] arr = file.getBytes();
               file.transferTo(f);
               return Result.success();
           }else{
               return Result.error("139","图片为空");
           }
       }catch (Exception e){
           e.printStackTrace();
           return Result.error("139",e.getMessage());
       }
    }

这里使用@RequestBody MultipartFile file,也可以使用@RequestParam("file") MultipartFile file,只要对应前端的参数名就行,formData.append('file',this.file.raw)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值