这篇文章主要介绍了文件上传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.bootspring-boot-starter-parent2.0.4.RELEASEorg.sangchapter011.0-SNAPSHOT org.springframework.bootspring-boot-starter-web org.springframework.bootspring-boot-maven-plugin
2、upload.html页面
<title>Title</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(); } S<strong style="color:transparent">来源gao@daima#com搞(%代@#码@网</strong>tring 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参数报空问题的解决办法的详细内容,更多请关注gaodaima搞代码网其它相关文章!