您的位置:首页 > 编程语言 > Java开发

SpringMVC使用进阶-文件上传

2014-12-11 21:58 357 查看
如今文件上传的方式已经是遍地开花,各种五花八门的文件上传有的时候着实让人难以抉择,如果是使用springmvc也不用为文件上传而发愁,springmvc的文件上传比struts2的那个还要简单,就是寥寥无几的一点代码就能解决上传。

1  修改之前的配置文件

spring主要是编写配置文件比较麻烦,配置文件正确是程序正确执行的关键,同样的springmvc如果要支持文件上传也需要加上如下配置;

<!-- 文件上传相关配置 -->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="defaultEncoding" value="gbk"/> <!-- 默认编码 (ISO-8859-1) -->
<property name="maxInMemorySize" value="10240"/> <!-- 最大内存大小 (10240)-->
<property name="uploadTempDir" value="/temp/"/> <!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->
<property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) -->
</bean>


2  文件上传界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
名称:<input type="text" name="name" /><br><br>
选择文件:<input type="file" name="image" /><br><br>
<input type="submit" value="确认上传"/>
</form>
</body>
</html>

无论jsp、php、asp.net上传文件一般都通过表单上传,而且还必须有enctype="multipart/form-data",否则文件将无法上传成功,还需要注意的一点就是springmvc的上传实现使用的是commons-io,因此相应的jar包也不能少。

3  文件上传控制器

package org.hncst.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class FileUploadController implements ServletContextAware{
private ServletContext servletContext;
public ServletContext getServletContext() {
return servletContext;
}

public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@RequestMapping(value="/upload.do", method = RequestMethod.POST)
public String uploadFile(String name,@RequestParam("image") CommonsMultipartFile file) {
String path=this.servletContext.getRealPath("/upload");
//取得原始的文件名
String fileName=file.getOriginalFilename();
//取得文件的后缀(包含点号)
String fileExt=fileName.substring(fileName.lastIndexOf("."));
//使用时间戳给文件命名
File file2=new File(path,new Date().getTime()+fileExt);
//将上传的文件保存起来
try {
file.getFileItem().write(file2);
} catch (Exception e) {

e.printStackTrace();

return "redirect:uploadFailure.jsp";
}
return "redirect:uploadSuccess.jsp";
}

}


这个上传的实现和struts有比较相似,都要取得上下文对象,struts和springmvc的做法大体类似,控制器都需要实现ServletContextAware接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springmvc