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

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


如下使用CommonsMultipartResolver:

@Configuration
public class FileConfig {

    @Resource
    private Environment env;
    /**
      * @Description: 临时文件存放的目录
      * @param null
      * @return: null
      * @Author Tian GuoPing
      * @Date: 2021/9/27 10:30
      * @Version 1.0
    **/
    public String getTempFileDir(){
        return env.getProperty("upload.temp.filepath");
    }
    
    /**
      * @Description: 文件最终存放的目录
      * @param null
      * @return: null
      * @Author Tian GuoPing
      * @Date: 2021/9/27 10:30
      * @Version 1.0
    **/
    public String getFileDir(){
        return env.getProperty("upload.filepath");
    }

    /**
      * @Description: CommonsMultipartResolver文件解析器,默认是StandardServletMultipartResolver
      * @param null
      * @return: null
      * @Author Tian GuoPing
      * @Date: 2021/9/27 10:30
      * @Version 1.0
    **/
    @Bean(name = "multipartResolver")
    public MultipartResolver getFileResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding(env.getProperty("upload.encode"));
        long maxSize = env.getProperty("upload.maxfilesize",Long.class);
        resolver.setMaxUploadSize(maxSize);
        try {
            String path = env.getProperty("upload.temp");
            FileSystemResource resource = new FileSystemResource(path);
            resolver.setUploadTempDir(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resolver;
    }
}

controller如下:

package com.base.fawu.controller;

import com.base.fawu.bean.Result;
import com.base.fawu.config.FileConfig;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * *@Author:蛋炒饭
 * *@Date:2021/9/27
 * *@Time:9:22
 * *@Year:2021
 * *@Month:09
 * 文件上传和下载
 **/
@RestController
@RequestMapping("/api")
public class FileOperatorController {

    @Resource
    private FileConfig fileConfig;
    /**
      * @Description: 多文件上传
      * @param files 文件
      * @return: null
      * @Author Tian GuoPing
      * @Date: 2021/9/27 9:57
      * @Version 1.0
    **/
    @PostMapping("/files")
    public Result uploadFiles(@RequestParam("files") MultipartFile[] files) throws IOException {
        Result rs = null;
        // 使用日期来分类管理上传的文件
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //先存临时文件
        File folder = new File( fileConfig.getRootDir()+fileConfig.getTempFileDir() + format+"/");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        StringBuilder paths = new StringBuilder();
        for (MultipartFile file : files) {
            if(file.isEmpty()){
                paths.append(",");
                continue;
            }
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            File newFile = new File(folder, newName);
            //保存文件
            file.transferTo(newFile);
            paths.append(fileConfig.getTempFileDir()+ format+"/"+newName+",");
        }
        rs = Result.ok();
        Map<String,Object> data = new HashMap(4);
        data.put("paths",paths);
        rs.setData(data);
        return rs;
    }


    /**
     * @Description: 单文件上传
     * @param file 文件
     * @return: null
     * @Author Tian GuoPing
     * @Date: 2021/9/27 9:57
     * @Version 1.0
     **/
    @PostMapping("/file")
    public Result uploadFile(@RequestParam MultipartFile file) throws Exception{
        // 使用日期来分类管理上传的文件
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //先存临时文件
        File folder = new File( fileConfig.getRootDir()+fileConfig.getTempFileDir() + format+"/");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        if(file==null||file.isEmpty()){
            return Result.error("文件不可以是空");
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        File newFile = new File(folder, newName);
        //保存文件
        file.transferTo(newFile);
        Result rs = Result.ok();
        Map<String,Object> data = new HashMap<>();
        data.put("path",fileConfig.getTempFileDir() + format+"/"+newName);
        rs.setData(data);
        return rs;
    }

    /**
      * @Description: 文件下载
      * @param fileName 指定下载文件名字
      * @param downloadFilePath 下载文件相对根目录路径
      * @return: null
      * @Author Tian GuoPing
      * @Date: 2021/9/27 11:08
      * @Version 1.0
    **/
    @GetMapping("/file")
    public ResponseEntity downloadFile(String fileName, String downloadFilePath) throws IOException {
        //下载文件,简单new个文件
        File downloadFile = new File(fileConfig.getRootDir()+downloadFilePath);
        String downloadFileName = "";
        if(fileName!=null){
            downloadFileName = fileName+downloadFilePath.substring(downloadFilePath.lastIndexOf("."));
        }
        else{
            downloadFileName = downloadFile.getName();
        }

        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名,并解决中文名称乱码问题
        downloadFileName = new String(downloadFileName.getBytes("UTF-8"),"iso-8859-1");
        //通知浏览器以attachment(下载方式)打开
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //applicatin/octet-stream: 二进制流数据(最常见的文件下载)
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 使用下org.apache.commons.io.FileUtils工具类
        byte[] bytes = FileUtils.readFileToByteArray(downloadFile);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }
}

application.xml配置如下:

#文件的根目录
upload.root=e:/file
#文件保存的临时目录
upload.temp.filepath=/temp/
#文件最后存的目录
upload.filePath=/upload/
#上传的时候产生临时文件的位置,临时文件上传完成会自动删除
upload.temp=/tempData
upload.encode=utf-8
#限制文件大小
upload.maxfilesize=5400000

postman测试:
在这里插入图片描述
后台报错信息:

org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present

解决:
参考这篇文章: Springboot的文件上传接口,使用postman测试一直报Required request part ‘file’ is not present错误.
在application.xml中添加配置,干掉springboot默认的配置:

#如果自己定义multipartResolver,需要关闭springboot的文件上传的自动配置,否则接收不到文件或者报错
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tianguoping

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值