1.环境搭建:
在maven的pom. 文件中导入两个依赖
1).commons-fileupload
2).commons-io
在resources目录下的springmvc. 文件中配置multipartResolver
<? version="1.0" encoding="UTF-8"?> <beans ns="http://www.spring work.org/schema/beans" ns:xsi="http://www.w3.org/2001/ Schema-instance" ns:context="http://www.spring work.org/schema/context" ns:mvc="http://www.spring work.org/schema/mvc" xsi:schemaLocation=" http://www.spring work.org/schema/context http://www.spring work.org/schema/context/spring-context.xsd http://www.spring work.org/schema/mvc http://www.spring work.org/schema/mvc/spring-mvc.xsd http://www.spring work.org/schema/beans http://www.spring work.org/schema/beans/spring-beans.xsd"> <!--包扫描--> <context:component-scan -package="cn.itcast"></context:component-scan> <!--配置multipartResolver,注意:id名称固定为multipartResolver--> <bean id="multipartResolver" class="org.spring work.web.multipart.commons.CommonsMultipartResolver"> </bean> <mvc:annotation-driven ></mvc:annotation-driven> <!--让静态资源不经过过滤器--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <!--视图解析器给controller中返回的逻辑视图名加上前缀和后缀--> <bean id="internalResourceViewResolver" class="org.spring work.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
2.编写前台测试jsp
<form action="/test/file" method="post" enctype="multipart/form-data">
上传的文件:<input type="file" name="upload"><br/>
密钥:<input type="text" name="password"><br/>
<input type="submit" value="提交">
</form>
注意页面三要素:
1).表单提交方式必须为post
2).表单中必须有file域,即type="file"
3).表单中enctype="multipart/form-data"
3.编写后台测试代码
@Controller @RequestMapping("/test") public class FileUploadController { @RequestMapping("/file") public String testFileUpload(HttpServletRequest request, MultipartFile upload) throws IOException { //upload是表单中文件name属性值,必须保持一致 System.out.println("testFileUpload..."); String realPath = request.getSession().getServletContext().getRealPath("/uploads"); File file = new File(realPath); if(!file.exists()){ file.mkdirs();//创建文件夹 } String filename = upload.getOriginalFilename(); //获取文件名 String name = upload.getName();//获取表单中的name属性值 即upload String uuid = UUID.randomUUID().toString().replaceAll("-", "");//生成uuid避免文件名重复导致冲突覆盖 filename=uuid+"_"+filename; upload.transferTo(new File(file,filename)); return "forward:success.jsp"; }
继续阅读与本文标签相同的文章
下一篇 :
一文总结机器学习类面试问题与思路
-
海思向公开市场推出首款4G通信芯片Balong 711
2026-05-18栏目: 教程
-
猫和老鼠:5种药水效果可以叠加吗?这2种药水效果会有冲突!
2026-05-18栏目: 教程
-
自媒体教程,深度剖析平台的推荐机制原理,了解怎么获取高流量
2026-05-18栏目: 教程
-
宽带故障怎么办?教你几招,轻松解决!
2026-05-18栏目: 教程
-
Python 3.8刚刚发布!一分钟了解新版本的强大功能!
2026-05-18栏目: 教程
