Spring MVC 파일 업로드 다운로드 인스턴스

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파일 다운로드
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기