文件上传报错: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
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐