栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

文件上传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参数报空 内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/130664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号