当前位置: 移动技术网 > IT编程>开发语言>Java > Spring MVC 文件上传下载的实例

Spring MVC 文件上传下载的实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring mvc 文件上传下载,具体如下:

(1) 导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。

(2) 在src/context/dispatcher.xml中添加

<bean id="multipartresolver" 
 class="org.springframework.web.multipart.commons.commonsmultipartresolver" 
 p:defaultencoding="utf-8" /> 

注意,需要在头部添加内容,添加后如下所示:

<beans default-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

/** 
 * 
 * @author geloin 
 */ 
package com.geloin.spring.util; 
 
import java.io.bufferedinputstream; 
import java.io.bufferedoutputstream; 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.fileoutputstream; 
import java.text.simpledateformat; 
import java.util.arraylist; 
import java.util.date; 
import java.util.hashmap; 
import java.util.iterator; 
import java.util.list; 
import java.util.map; 
 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
 
import org.apache.tools.zip.zipentry; 
import org.apache.tools.zip.zipoutputstream; 
import org.springframework.util.filecopyutils; 
import org.springframework.web.multipart.multipartfile; 
import org.springframework.web.multipart.multiparthttpservletrequest; 
 
public class fileoperateutil { 
 private static final string realname = "realname"; 
 private static final string storename = "storename"; 
 private static final string size = "size"; 
 private static final string suffix = "suffix"; 
 private static final string contenttype = "contenttype"; 
 private static final string createtime = "createtime"; 
 private static final string uploaddir = "uploaddir/"; 
 
 /** 
  * 将上传的文件进行重命名 
  * 
  * @param name 
  * @return 
  */ 
 private static string rename(string name) { 
 
  long now = long.parselong(new simpledateformat("yyyymmddhhmmss") 
    .format(new date())); 
  long random = (long) (math.random() * now); 
  string filename = now + "" + random; 
 
  if (name.indexof(".") != -1) { 
   filename += name.substring(name.lastindexof(".")); 
  } 
 
  return filename; 
 } 
 
 /** 
  * 压缩后的文件名 
  * 
  * @param name 
  * @return 
  */ 
 private static string zipname(string name) { 
  string prefix = ""; 
  if (name.indexof(".") != -1) { 
   prefix = name.substring(0, name.lastindexof(".")); 
  } else { 
   prefix = name; 
  } 
  return prefix + ".zip"; 
 } 
 
 /** 
  * 上传文件 
  * 
  * @param request 
  * @param params 
  * @param values 
  * @return 
  * @throws exception 
  */ 
 public static list<map<string, object>> upload(httpservletrequest request, 
   string[] params, map<string, object[]> values) throws exception { 
 
  list<map<string, object>> result = new arraylist<map<string, object>>(); 
 
  multiparthttpservletrequest mrequest = (multiparthttpservletrequest) request; 
  map<string, multipartfile> filemap = mrequest.getfilemap(); 
 
  string uploaddir = request.getsession().getservletcontext() 
    .getrealpath("/") 
    + fileoperateutil.uploaddir; 
  file file = new file(uploaddir); 
 
  if (!file.exists()) { 
   file.mkdir(); 
  } 
 
  string filename = null; 
  int i = 0; 
  for (iterator<map.entry<string, multipartfile>> it = filemap.entryset() 
    .iterator(); it.hasnext(); i++) { 
 
   map.entry<string, multipartfile> entry = it.next(); 
   multipartfile mfile = entry.getvalue(); 
 
   filename = mfile.getoriginalfilename(); 
 
   string storename = rename(filename); 
 
   string nozipname = uploaddir + storename; 
   string zipname = zipname(nozipname); 
 
   // 上传成为压缩文件 
   zipoutputstream outputstream = new zipoutputstream( 
     new bufferedoutputstream(new fileoutputstream(zipname))); 
   outputstream.putnextentry(new zipentry(filename)); 
   outputstream.setencoding("gbk"); 
 
   filecopyutils.copy(mfile.getinputstream(), outputstream); 
 
   map<string, object> map = new hashmap<string, object>(); 
   // 固定参数值对 
   map.put(fileoperateutil.realname, zipname(filename)); 
   map.put(fileoperateutil.storename, zipname(storename)); 
   map.put(fileoperateutil.size, new file(zipname).length()); 
   map.put(fileoperateutil.suffix, "zip"); 
   map.put(fileoperateutil.contenttype, "application/octet-stream"); 
   map.put(fileoperateutil.createtime, new date()); 
 
   // 自定义参数值对 
   for (string param : params) { 
    map.put(param, values.get(param)[i]); 
   } 
 
   result.add(map); 
  } 
  return result; 
 } 
 
 /** 
  * 下载 
  * @param request 
  * @param response 
  * @param storename 
  * @param contenttype 
  * @param realname 
  * @throws exception 
  */ 
 public static void download(httpservletrequest request, 
   httpservletresponse response, string storename, string contenttype, 
   string realname) throws exception { 
  response.setcontenttype("text/html;charset=utf-8"); 
  request.setcharacterencoding("utf-8"); 
  bufferedinputstream bis = null; 
  bufferedoutputstream bos = null; 
 
  string ctxpath = request.getsession().getservletcontext() 
    .getrealpath("/") 
    + fileoperateutil.uploaddir; 
  string downloadpath = ctxpath + storename; 
 
  long filelength = new file(downloadpath).length(); 
 
  response.setcontenttype(contenttype); 
  response.setheader("content-disposition", "attachment; filename=" 
    + new string(realname.getbytes("utf-8"), "iso8859-1")); 
  response.setheader("content-length", string.valueof(filelength)); 
 
  bis = new bufferedinputstream(new fileinputstream(downloadpath)); 
  bos = new bufferedoutputstream(response.getoutputstream()); 
  byte[] buff = new byte[2048]; 
  int bytesread; 
  while (-1 != (bytesread = bis.read(buff, 0, buff.length))) { 
   bos.write(buff, 0, bytesread); 
  } 
  bis.close(); 
  bos.close(); 
 } 
} 

可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在webcontent/uploaddir下。

(4) 添加fileoperatecontroller.java

/** 
 * 
 * @author geloin 
 */ 
package com.geloin.spring.controller; 
 
import java.util.hashmap; 
import java.util.list; 
import java.util.map; 
 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
 
import org.springframework.stereotype.controller; 
import org.springframework.web.bind.servletrequestutils; 
import org.springframework.web.bind.annotation.requestmapping; 
import org.springframework.web.servlet.modelandview; 
 
import com.geloin.spring.util.fileoperateutil; 
 
@controller 
@requestmapping(value = "background/fileoperate") 
public class fileoperatecontroller { 
 /** 
  * 到上传文件的位置 
  * @return 
  */ 
 @requestmapping(value = "to_upload") 
 public modelandview toupload() { 
  return new modelandview("background/fileoperate/upload"); 
 } 
 
 /** 
  * 上传文件 
  * 
  * @param request 
  * @return 
  * @throws exception 
  */ 
 @requestmapping(value = "upload") 
 public modelandview upload(httpservletrequest request) throws exception { 
 
  map<string, object> map = new hashmap<string, object>(); 
 
  // 别名 
  string[] alaises = servletrequestutils.getstringparameters(request, 
    "alais"); 
 
  string[] params = new string[] { "alais" }; 
  map<string, object[]> values = new hashmap<string, object[]>(); 
  values.put("alais", alaises); 
 
  list<map<string, object>> result = fileoperateutil.upload(request, 
    params, values); 
 
  map.put("result", result); 
 
  return new modelandview("background/fileoperate/list", map); 
 } 
 
 /** 
  * 下载 
  * 
  * @param attachment 
  * @param request 
  * @param response 
  * @return 
  * @throws exception 
  */ 
 @requestmapping(value = "download") 
 public modelandview download(httpservletrequest request, 
   httpservletresponse response) throws exception { 
 
  string storename = "201205051340364510870879724.zip"; 
  string realname = "java设计模式.zip"; 
  string contenttype = "application/octet-stream"; 
 
  fileoperateutil.download(request, response, storename, contenttype, 
    realname); 
 
  return null; 
 } 
} 

下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考spring mvc 整合mybatis实例。

(5) 添加fileoperate/upload.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8" 
 pageencoding="utf-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<!doctype html 
public "-//w3c//dtd xhtml 1.0 transitional//en" 
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
<title>insert title here</title> 
</head> 
<body> 
</body> 
<form enctype="multipart/form-data" 
 action="<c:url value="/background/fileoperate/upload.html" />" method="post"> 
 <input type="file" name="file1" /> <input type="text" name="alais" /><br /> 
 <input type="file" name="file2" /> <input type="text" name="alais" /><br /> 
 <input type="file" name="file3" /> <input type="text" name="alais" /><br /> 
 <input type="submit" value="上传" /> 
</form> 
</html> 

 确保enctype的值为multipart/form-data;method的值为post。

(6) 添加fileoperate/list.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8" 
 pageencoding="utf-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<!doctype html 
public "-//w3c//dtd xhtml 1.0 transitional//en" 
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
<title>insert title here</title> 
</head> 
<body> 
 <c:foreach items="${result }" var="item"> 
  <c:foreach items="${item }" var="m"> 
   <c:if test="${m.key eq '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下载文件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网