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下载文件

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

(0)

相关推荐

  • 在SpringMVC框架下实现文件的上传和下载示例

    在eclipse中的javaEE环境下:导入必要的架包 web.xml的配置文件: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation=&

  • springMVC配置环境实现文件上传和下载

    最近的项目中用到了文件的上传和下载功能,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试. 下面就是springMVC配置环境实现文件上传和下载的具体步骤,供大家参考,具体内容如下 一. 基础配置: maven导包及配置pom.xml,导包时除开springmvc的基础依赖外,需要导入文件上传下载时用到的commons-io.jsr和commons-fileupload.jar: <project xmlns="http://maven.apache.org/POM/4.0.0&

  • SpringMvc3+extjs4实现上传与下载功能

    最近生活过的很充实,人一直在不停的忙碌着学习新东西.这是我最近遇到的问题,我找度娘n了很久,终于找到了解决方案! 前台代码: <script> Ext.onReady(function() { Ext.create('Ext.form.Panel', { title : '文件上传', width : 400, bodyPadding : 10, frame : true, renderTo : document.body, items : [ { xtype : 'filefield', n

  • MyBatis与SpringMVC相结合实现文件上传、下载功能

    环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中:如何从数据库下载文件,和显示图像文件并实现缩放. 将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob. 首先要创建数据库,此处使用MySql数据库. 注意:文中给出的代码多为节选重要片段,并不齐全. 1. 前期准备 使用maven创建一个springMVC+spring+mybatis+mysql的项目

  • SpringMVC实现文件的上传和下载实例代码

    前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:"用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流".我回复他说:"使用SpringMVC框架可以做到这一点,因为SpringMVC为文件的上传提供了直接的支持,但需要依赖Apache提供Commons FileUpload组件jar包."鉴于这个问题,我上网也百度了一下,网上很多都是介绍的使用IO流来实现文件的上传和下载,也有说到框架的,但介绍的并不是很完整,今天小钱将和大家介绍使用Spr

  • SpringMVC文件上传 多文件上传实例

    必须明确告诉DispatcherServlet如何处理MultipartRequest.SpringMVC中提供了文件上传使用方式如下配置xxx-servlet.xml,添加如下代码: 复制代码 代码如下: <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          <!-- 设置

  • Spring MVC中上传文件实例

    SpringMVC(注解)上传文件需要注意的几个地方: 1.form的enctype="multipart/form-data",这个是上传文件必须的 2.applicationContext.xml配置: 复制代码 代码如下: <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.w

  • 基于Spring Mvc实现的Excel文件上传下载示例

    最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring mvc的项目如何搭建,传送门在这里. 这次就基于这个工程,继续实现上传下载的小例子.需要做下面的事情: 1 增加index.html,添加form提交文件 2 引入commons-fileupload.commons-io.jxl等工具包 3 创建upload download接口 4 注入mul

  • Java Spring MVC 上传下载文件配置及controller方法详解

    下载: 1.在spring-mvc中配置(用于100M以下的文件下载) <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!--配置下载返回类型--> <bean class="or

  • 学习SpringMVC——国际化+上传+下载详解

    一个软件,一个产品,都是一点点开发并完善起来的,功能越来越多,性能越来越强,用户体验越来越好--这每个指标的提高都需要切切实实的做点东西出来,好比,你的这个产品做大了,用的人多了,不仅仅再是上海人用,北京人用,还有印度人用,法国人用等等,可以说这个产品已经走上了国际化的大舞台.当印度的哥们输入url访问产品时,界面上弹出"欢迎您,三哥",估计哥们当场就蒙圈了.而这个时候,国际化就应运而生了. 要做国际化这道菜,真的没有想象中的那么复杂,反而很简单,不信你看-- 1. 注入Resourc

随机推荐