一、CommonsMultipartResolver
在使用springMVC进行系统实现时,springMVC默认的解析器里面是没有加入对文件上传的解析的。但如果你想使用springMVC对文件上传的解析器来处理文件上传的时候就需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明。这样之后,客户端每次进行请求的时候,springMVC都会检查request里面是否包含多媒体信息,如果包含了就会使用MultipartResolver进行解析,springMVC会使用一个支持文件处理的MultipartHttpServletRequest来包裹当前的HttpServletRequest,然后使用MultipartHttpServletRequest就可以对文件进行处理了。Spring已经为我们提供了一个MultipartResolver的实现,我们只需要拿来用就可以了,那就是org.springframework.web.multipart.commons.CommsMultipartResolver。因为springMVC的MultipartResolver底层使用的是Commons-fileupload,所以还需要加入对Commons-fileupload.jar的支持。
需要导入的jar包:
配置文件springmvc.xml
<!-- 定义文件上传解析器
这里申明的id必须为multipartResolver
SpringMVC上传文件时,需要配置MultipartResolver处理器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 表示用来解析request请求的默认编码格式,当没有指定的时候根据Servlet规范会使用默认值ISO-
8859-1。当request自己指明了它的编码格式的时候就会忽略这里指定的defaultEncoding -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 设定文件上传的最大值为5MB,5*1024*1024
设置允许上传的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1-->
<property name="maxUploadSize" value="5242880"/>
<!-- 设定文件上传时允许写入内存的最大值,如果小于这个参数不会生成临时文件,默认为10240 -->
<property name="maxInMemorySize" value="40960"/>
<!-- 上传文件的临时路径,默认是Servlet容器的临时目录 -->
<property name="uploadTempDir" value="fileUpload/temp"/>
<!-- 延迟文件解析 -->
<property name="resolveLazily" value="true"/>
</bean>
二、实例
html代码:
<div class="input-file" id="Models_selection_style">
<input type="text" id="avatval" placeholder="请选择文件..." readonly="readonly"
style="vertical-align: middle;" />
<input type="file" name="file" id="avatar" />
<a href="javascript:void(0);" class="button-selectimg" id="avatsel">选择文件</a>
<input type="button" onclick="postData()" name="" id="" value="上传文件" />
<div style="float: right">
<input id="search" type="text" placeholder="搜索...">
<input id="search_button" type="button" onclick="" style="cursor: pointer;"
value="搜索">
</div>
</div>
js代码:
function postData(){
// 创建表单数据对象
var formData = new FormData();
// 获取文件框中的数据
var file = document.getElementById("avatar").files[0];
// 将文件数据添加至表单数据对象中
formData.append("file", file);
$.ajax({
type:"post",
url:"<%=basePath%>file/fileUpload",
data:formData,
contentType: false,
processData: false,
mimeType:"multipart/form-data",
dataType:"text",
success:function(res){
//
},
error:function(res){
//
}
})
}
java代码:
@Controller
@RequestMapping(value = "file")
public class UpAndDownController {
/**
* 通过流的方式上传文件 @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
* @throws IOException
*/
@RequestMapping(value = "fileUpload")
public void fileUpload(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "desc", required = false) String desc,
@RequestParam("file") CommonsMultipartFile file) throws IOException {
response.setContentType("application/text; charset=utf-8");
PrintWriter writer = response.getWriter();
ServletContext servletContext = request.getSession().getServletContext();// 获取ServletContext的对象 代表当前WEB应用
String realPath = servletContext.getRealPath("/uploads");// 得到文件上传目的位置的真实路径
realPath = "D:/upload";
File file1 = new File(realPath);
if (!file1.exists()) {
file1.mkdir(); // 如果该目录不存在,就创建此抽象路径名指定的目录。
}
String prefix = UUID.randomUUID().toString();
prefix = prefix.replace("-", "");
String fileName = prefix + "_" + file.getOriginalFilename();// 使用UUID加前缀命名文件,防止名字重复被覆盖
try {
InputStream in;
in = file.getInputStream();
// 声明输入输出流
OutputStream out = new FileOutputStream(new File(realPath + File.separator + fileName));// 指定输出流的位置;
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush(); // 类似于文件复制,将文件存储到输入流,再通过输出流写入到上传位置
} // 这段代码也可以用IOUtils.copy(in, out)工具类的copy方法完成
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
writer.write("failure!");
}
writer.write("success!");
}
}
最终效果是可选择文件上传,并显示到页面供操作,如删除、下载等。效果图如下: