这篇文章给大家分享的是有关springmvc怎样实现文件上传功能的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
一个简单的springmvc文件上传例子
所需的依赖
只需要这个就好了。在idea的依赖关系图中,commons-fileupload包含了commons-io依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
一个简单的文件上传的页面
<form action="http://localhost:8080/springmvc_Web_exploded/fff" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filer_input" multiple="multiple">
<input type="submit" value="Submit">
</form>
在spring的配置文件中注入一个文件上传的bean
spring.xml
<!-- 文件上传的bean-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件的最大大小,单位为字节 -->
<property name="maxUploadSize" value="17367648787"></property>
<!-- 上传文件的编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
实例代码
@PostMapping("/fff")
public String file(@PathVariable("file")MultipartFile file, HttpServletRequest req) throws IOException {
//判断文件不存在
if (file.isEmpty()){
return "faile.html";
}
//我想放到这个地方文件的路径
String realPath = req.getServletContext().getRealPath("/WEB-INF/file");
//返回客户端文件系统中的原始文件名
String filename = file.getOriginalFilename();
File myFile = new File(realPath, filename);
if (!myFile.getParentFile().exists()){
myFile.getParentFile().mkdir();
System.out.println("文件夹被创建了");
}
//将前端传过来的文件,传到自己new的File对象中
file.transferTo(myFile);
return "success.html";
}
注意事项:
1、文件上传请求必须用post请求。
2、注意路径问题
3、前端的form表单必须添加 enctype="multipart/form-data" 这个属性
感谢各位的阅读!关于“springmvc怎样实现文件上传功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。