SpringMVC使用MultipartResolver实现文件上传
SpringMVC 中,文件的上传,是通过 MultipartResolver 实现的。 所以,如果要实现文
件的上传,只要在 spring-mvc.xml 中注册相应的 MultipartResolver 即可。
MultipartResolver 的实现类有两个:
- CommonsMultipartResolver
- StandardServletMultipartResolver
两个的区别:
- 第一个需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比较旧的servlet 版本中使用。
- 第二个不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在Servlet 3 以上的版本使用。
我们这里使用第一种来实现上传。
1.导入依赖
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2.再application中添加配置
<!-- 多部分文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="104857600"/> <property name="maxInMemorySize" value="4096"/> </bean>
**maxUploadSize:**设置允许上传文件的最大值,以字节为单位。默认为-1,表示无限制。
**defaultEncoding:**表示用来请求解析request请求的默认编码格式,当没有指定时默认使用ISO-8859-1。当request自己指明了他的编码格式的时候就会忽略这里的defaultEncoding。
3.编写controller代码
@Autowired private HttpServletRequest request; @PostMapping("native") public String nativeUpload(@RequestParam("file") MultipartFile file, String folder) throws UnsupportedEncodingException { // 拿到webapp下面img文件夹的位置 String path = request.getSession().getServletContext().getRealPath("img"); // getOriginalFilename获取文件的原始名称,例如:2.jpg String filePath = path + "\\" + file.getOriginalFilename(); File destFile = new File(filePath); // 如果目录不存在 if (!destFile.getParentFile().exists()) { // 创建目录(可能位多层) destFile.mkdirs(); } // destFile:目标文件 try { file.transferTo(destFile); } catch (IOException e) { e.printStackTrace(); } String res = "http://localhost:9101/img/" + file.getOriginalFilename(); return new String(res.getBytes(), "UTF-8"); }
这里MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称
到此这篇关于SpringMVC使用MultipartResolver实现文件上传的文章就介绍到这了,更多相关SpringMVC MultipartResolver内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring中的@PropertySource注解源码详细解析
这篇文章主要介绍了Spring中的@PropertySource注解源码详细解析,@PropertySource注解,标注在配置类@Configuration上面,下面主要分析一下@PropertySource注解的处理过程,也就是怎么把配置信息从.properies文件放到environment中的,需要的朋友可以参考下2024-01-01SpringAnimation 实现菜单从顶部弹出从底部消失动画效果
最近做项目遇到这样一个需求,要求实现一种菜单,菜单从顶部弹入,然后从底部消失,顶部弹入时,有一个上下抖动的过程,底部消失时,先向上滑动,然后再向下滑动消失。下面给大家带来了实现代码,感兴趣的朋友一起看看吧2018-05-05Java8 CompletableFuture 异步执行操作
CompletableFuture是java8提供的基于异步操作的封装,日常开发中经常会用到,接下来通过本文给大家介绍Java8 CompletableFuture 异步执行操作,感兴趣的朋友一起看看吧2021-06-06解决Unable to start embedded container&nbs
这篇文章主要介绍了解决Unable to start embedded container SpringBoot启动报错问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-07-07
最新评论