• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

springboot 搞代码 4年前 (2022-01-05) 48次浏览 已收录 0个评论

这篇文章主要介绍了文件上传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搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:文件上传SpringBoot后端MultipartFile参数报空问题的解决办法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址