Spring MVC 文件上传下载的实例
SpringMVC文件上传下载,具体如下:
(1)导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。
(2)在src/context/dispatcher.xml中添加
<beanid="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8"/>
注意,需要在头部添加内容,添加后如下所示:
<beansdefault-lazy-init="true" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
(3)添加工具类FileOperateUtil.java
/**
*
*@authorgeloin
*/
packagecom.geloin.spring.util;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.tools.zip.ZipEntry;
importorg.apache.tools.zip.ZipOutputStream;
importorg.springframework.util.FileCopyUtils;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.multipart.MultipartHttpServletRequest;
publicclassFileOperateUtil{
privatestaticfinalStringREALNAME="realName";
privatestaticfinalStringSTORENAME="storeName";
privatestaticfinalStringSIZE="size";
privatestaticfinalStringSUFFIX="suffix";
privatestaticfinalStringCONTENTTYPE="contentType";
privatestaticfinalStringCREATETIME="createTime";
privatestaticfinalStringUPLOADDIR="uploadDir/";
/**
*将上传的文件进行重命名
*
*@paramname
*@return
*/
privatestaticStringrename(Stringname){
Longnow=Long.parseLong(newSimpleDateFormat("yyyyMMddHHmmss")
.format(newDate()));
Longrandom=(long)(Math.random()*now);
StringfileName=now+""+random;
if(name.indexOf(".")!=-1){
fileName+=name.substring(name.lastIndexOf("."));
}
returnfileName;
}
/**
*压缩后的文件名
*
*@paramname
*@return
*/
privatestaticStringzipName(Stringname){
Stringprefix="";
if(name.indexOf(".")!=-1){
prefix=name.substring(0,name.lastIndexOf("."));
}else{
prefix=name;
}
returnprefix+".zip";
}
/**
*上传文件
*
*@paramrequest
*@paramparams
*@paramvalues
*@return
*@throwsException
*/
publicstaticList<Map<String,Object>>upload(HttpServletRequestrequest,
String[]params,Map<String,Object[]>values)throwsException{
List<Map<String,Object>>result=newArrayList<Map<String,Object>>();
MultipartHttpServletRequestmRequest=(MultipartHttpServletRequest)request;
Map<String,MultipartFile>fileMap=mRequest.getFileMap();
StringuploadDir=request.getSession().getServletContext()
.getRealPath("/")
+FileOperateUtil.UPLOADDIR;
Filefile=newFile(uploadDir);
if(!file.exists()){
file.mkdir();
}
StringfileName=null;
inti=0;
for(Iterator<Map.Entry<String,MultipartFile>>it=fileMap.entrySet()
.iterator();it.hasNext();i++){
Map.Entry<String,MultipartFile>entry=it.next();
MultipartFilemFile=entry.getValue();
fileName=mFile.getOriginalFilename();
StringstoreName=rename(fileName);
StringnoZipName=uploadDir+storeName;
StringzipName=zipName(noZipName);
//上传成为压缩文件
ZipOutputStreamoutputStream=newZipOutputStream(
newBufferedOutputStream(newFileOutputStream(zipName)));
outputStream.putNextEntry(newZipEntry(fileName));
outputStream.setEncoding("GBK");
FileCopyUtils.copy(mFile.getInputStream(),outputStream);
Map<String,Object>map=newHashMap<String,Object>();
//固定参数值对
map.put(FileOperateUtil.REALNAME,zipName(fileName));
map.put(FileOperateUtil.STORENAME,zipName(storeName));
map.put(FileOperateUtil.SIZE,newFile(zipName).length());
map.put(FileOperateUtil.SUFFIX,"zip");
map.put(FileOperateUtil.CONTENTTYPE,"application/octet-stream");
map.put(FileOperateUtil.CREATETIME,newDate());
//自定义参数值对
for(Stringparam:params){
map.put(param,values.get(param)[i]);
}
result.add(map);
}
returnresult;
}
/**
*下载
*@paramrequest
*@paramresponse
*@paramstoreName
*@paramcontentType
*@paramrealName
*@throwsException
*/
publicstaticvoiddownload(HttpServletRequestrequest,
HttpServletResponseresponse,StringstoreName,StringcontentType,
StringrealName)throwsException{
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
StringctxPath=request.getSession().getServletContext()
.getRealPath("/")
+FileOperateUtil.UPLOADDIR;
StringdownLoadPath=ctxPath+storeName;
longfileLength=newFile(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition","attachment;filename="
+newString(realName.getBytes("utf-8"),"ISO8859-1"));
response.setHeader("Content-Length",String.valueOf(fileLength));
bis=newBufferedInputStream(newFileInputStream(downLoadPath));
bos=newBufferedOutputStream(response.getOutputStream());
byte[]buff=newbyte[2048];
intbytesRead;
while(-1!=(bytesRead=bis.read(buff,0,buff.length))){
bos.write(buff,0,bytesRead);
}
bis.close();
bos.close();
}
}
可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在WebContent/uploadDir下。
(4)添加FileOperateController.Java
/**
*
*@authorgeloin
*/
packagecom.geloin.spring.controller;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.ServletRequestUtils;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.servlet.ModelAndView;
importcom.geloin.spring.util.FileOperateUtil;
@Controller
@RequestMapping(value="background/fileOperate")
publicclassFileOperateController{
/**
*到上传文件的位置
*@return
*/
@RequestMapping(value="to_upload")
publicModelAndViewtoUpload(){
returnnewModelAndView("background/fileOperate/upload");
}
/**
*上传文件
*
*@paramrequest
*@return
*@throwsException
*/
@RequestMapping(value="upload")
publicModelAndViewupload(HttpServletRequestrequest)throwsException{
Map<String,Object>map=newHashMap<String,Object>();
//别名
String[]alaises=ServletRequestUtils.getStringParameters(request,
"alais");
String[]params=newString[]{"alais"};
Map<String,Object[]>values=newHashMap<String,Object[]>();
values.put("alais",alaises);
List<Map<String,Object>>result=FileOperateUtil.upload(request,
params,values);
map.put("result",result);
returnnewModelAndView("background/fileOperate/list",map);
}
/**
*下载
*
*@paramattachment
*@paramrequest
*@paramresponse
*@return
*@throwsException
*/
@RequestMapping(value="download")
publicModelAndViewdownload(HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
StringstoreName="201205051340364510870879724.zip";
StringrealName="Java设计模式.zip";
StringcontentType="application/octet-stream";
FileOperateUtil.download(request,response,storeName,contentType,
realName);
returnnull;
}
}
下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考SpringMVC整合Mybatis实例。
(5)添加fileOperate/upload.jsp
<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPEhtml PUBLIC"-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/> <title>Inserttitlehere</title> </head> <body> </body> <formenctype="multipart/form-data" action="<c:urlvalue="/background/fileOperate/upload.html"/>"method="post"> <inputtype="file"name="file1"/><inputtype="text"name="alais"/><br/> <inputtype="file"name="file2"/><inputtype="text"name="alais"/><br/> <inputtype="file"name="file3"/><inputtype="text"name="alais"/><br/> <inputtype="submit"value="上传"/> </form> </html>
确保enctype的值为multipart/form-data;method的值为post。
(6)添加fileOperate/list.jsp
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPEhtml
PUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/>
<title>Inserttitlehere</title>
</head>
<body>
<c:forEachitems="${result}"var="item">
<c:forEachitems="${item}"var="m">
<c:iftest="${m.keyeq'realName'}">
${m.value}
</c:if>
<br/>
</c:forEach>
</c:forEach>
</body>
</html>
(7)通过http://localhost:8080/spring_test/background/fileOperate/to_upload.html访问上传页面,通过http://localhost:8080/spring_test/background/fileOperate/download.html下载文件
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。