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
回答: 当在上传文件时出现"Required request part 'file' is not present"的错误时,可能有几个原因。首先,这个错误可能是因为获取上传文件的名字不唯一导致的。确保在HTML代码中的<input>标签的name属性设置为"file",并且确保只有一个<input>标签具有这个name属性。\[1\] 另外,这个错误也可能是因为在使用FormData对象时出现了问题。确保在JavaScript代码中正确地创建了FormData对象,并且使用append()方法将文件添加到FormData对象中。例如,可以使用以下代码来创建FormData对象并添加文件: var form = new FormData(); form.append("file", document.getElementById("file").files\[0\]); 此外,还有一种可能是使用Postman测试时出现了这个错误。确保在Postman中正确设置了请求的Content-Type为"multipart/form-data",并且在请求中包含了正确的文件参数名。\[2\] 最后,如果你使用的是Spring Boot框架,这个错误可能是由于缺少请求的文件部分导致的。确保在后端代码中正确处理文件上传请求,并且使用@RequestParam注解来指定请求中的文件参数名。\[3\] 综上所述,要解决"Required request part 'file' is not present"的错误,你需要确保获取上传文件的名字唯一,正确创建并使用FormData对象,正确设置Postman请求的Content-Type,以及在后端代码中正确处理文件上传请求。 #### 引用[.reference_title] - *1* [文件上传Required request part ‘file’ is not present](https://blog.csdn.net/qq_39851647/article/details/123192052)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Springboot文件上传接口,一直报Required request part ‘zipFile‘ is not present的错误](https://blog.csdn.net/ylx1066863710/article/details/120652555)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [springcloud上传文件提示wMissingServletRequestPartException: Required request part ‘advert‘ is not ...](https://blog.csdn.net/qq_37844454/article/details/115306138)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Tianguoping

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

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

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

打赏作者

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

抵扣说明:

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

余额充值