文件上传SpringBoot后端MultipartFile参数报空问题的解决办法

最近写了一个文件上传的小demo,就是简单的前端html页面,后端controller接收,但是后端一直报错文件为null,看了很多文章,有说spring-boot自带的org.springframework.web.multipart.MultipartFile和Multipart冲突了,要在启动类中加入@EnableAutoConfiguration(exclue={MultipartAutoConfiguration.class}),有说要在MultipartFile参数前加上@RequestParam(“file”)以表明该参数类型是文件类型,还有说是前端表单没有设置enctype=“multipart/form-data”,参照上面方法我还是没有解决问题,后来更换了spring-boot版本就好了,代码如下:

1、pom.xml(注意我这里用的是2.0.4版本)



  4.0.0
  
    org.springframework.boot
    spring-boot-starter-parent
    2.0.4.RELEASE
  
  org.sang
  chapter01
  1.0-SNAPSHOT
  
    
      org.springframework.boot
      spring-boot-starter-web
    
  
  
    
      
        org.springframework.boot
        spring-boot-maven-plugin
      
    
  

2、upload.html页面




  
  Title


3、后端controller

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileUploadController {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
  @PostMapping("upload")
  public String upload(MultipartFile uploadFile, HttpServletRequest req){
    String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
    String format = sdf.format(new Date());
    File folder = new File(realPath+format);
    if(!folder.isDirectory()){
      folder.mkdirs();
    }
    String oldName = uploadFile.getOriginalFilename();
    String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
    try{
      uploadFile.transferTo(new File(folder,newName));
      String path = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/uploadFile/"+format+newName;
      return path;
    }catch (IOException e){
      e.printStackTrace();
    }
    return "上传失败";
  }
}

到此这篇关于文件上传SpringBoot后端MultipartFile参数报空问题的解决办法的文章就介绍到这了,更多相关SpringBoot MultipartFile参数报空 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(文件上传SpringBoot后端MultipartFile参数报空问题的解决办法)