springmvc文件上传

来源:互联网 发布:约翰斯塔克斯数据 编辑:程序博客网 时间:2024/04/20 23:42

加入文件上传所需jar包:commons-fileupload和commons-io

1.在jsp页面中为form表单配置enctype="multipart/form-data"

2.在springmvc的配置文件中添加:

<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  

    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->  
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
            </props>  
        </property>  
    </bean> 

3.创建虚拟目录:

第一种方式:


第二种方式:

修改tomcat的配置文件

在tomcat下conf/server.xml的<Host>标签中添加:

<Context docBase="D:\img" path="/pic" reloadable="false"/>。

访问http://localhost:8080/pic即可访问D:\img下的图片。

controller中的方法:

//保存修改页面
@RequestMapping(value="/updSave")
public String updSave(User user, MultipartFile userPic) {

//上传图片
//上传图片的原始名称
String origianlFileName = userPic.getOriginalFilename();
if (userPic != null && origianlFileName != null && origianlFileName.length() > 0) {
//存储图片的物理路径
String pic_path = "D:\\img\\";
//按照一定规律生成新的图片名称
String newFileName = UUID.randomUUID() + origianlFileName.substring(origianlFileName.lastIndexOf("."));
//新的图片
File newFile = new File(pic_path, newFileName);
//将内存中的数据写入磁盘
try {
userPic.transferTo(newFile);
//上传成功之后将图片名称(newFileName)写入数据库表对应的字段中。
user.setPic(newFileName);

} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
userServiceImpl.updSave(user);
}


return "redirect:findUsers";
}

页面中的代码为(不是添加用户页面,是编辑用户页面,所以有一个判断语句):


注意:页面中file的name属性和controller中形参MultipartFile 的名称保持一致。















1 0