首页 > 代码库 > springmvc单文件上传
springmvc单文件上传
1.创建上传页面
<form action="first.do" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFile" value="http://www.mamicode.com/选择文件" /> <input type="submit" value="提交" /> </form>
2.配置控制器
@Controller public class MyController { // 处理器方法 @RequestMapping(value = "http://www.mamicode.com/first.do") public String doFirst(HttpSession session, MultipartFile uploadFile) throws Exception { // 1.获取文件名称 String originalFilename = uploadFile.getOriginalFilename(); // 6.必须选择上传文件 if (uploadFile.getSize() > 0) { // 5.限制文件类型 if (originalFilename.endsWith("jpg") || originalFilename.endsWith("png") || originalFilename.endsWith("txt")) { // 2.获取保存的前路径 String servletContext = session.getServletContext() .getRealPath("upload"); System.out.println(servletContext); // 3.拼接路径 File realPath = new File(servletContext, originalFilename); // 4.保存 uploadFile.transferTo(realPath); return "/two.jsp"; } } return "/error.jsp"; } }
3.配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 扫描包中注解标注的类 --> <context:component-scan base-package="cn.cnsdhzzl.controller" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置编码 --> <property name="defaultEncoding" value="http://www.mamicode.com/UTF-8" /> <!-- 设置上传文件总大小 --> <property name="maxUploadSize" value="http://www.mamicode.com/5000" /> <!-- 设置单个上传文件大小 --> <property name="maxUploadSizePerFile" value="http://www.mamicode.com/1000" /> </bean> <mvc:annotation-driven /> </beans>
springmvc单文件上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。