spring mvc 文件上传

    本文基于Spring MVC 注解,让Spring跑起来

    方法一:
 


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/**
 * 文件操作工具类
 * @author jinghao@duohuo
 * @date   2014-2-26	
 * @version 1.0
 */
public class FileUtil extends FileUtils{
	
	/**
	 * 上传文件
	 * @param request
	 * @param fileAs
	 * @param baseFolder
	 * @return
	 * @throws IOException
	 */
	public static String uploadFile(MultipartHttpServletRequest request, String fileAs, String baseFolder) throws IOException{
		if(request==null) return null;
		List<MultipartFile> files=request.getFiles(fileAs);
		if(files.size()>0){
			 MultipartFile upFile=files.get(0);
			 String oldFileName = upFile.getOriginalFilename();
			 if(oldFileName==null||oldFileName.equals("")) return null;
			 String fileType = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
			 Date now = new Date();
		     SimpleDateFormat f = new SimpleDateFormat("yyyy"+File.separator+"MM");
		     String abPath = request.getServletContext().getRealPath(baseFolder);
		     String mytimepath=f.format(now);
		     File dir = new File(abPath + File.separator + mytimepath + File.separator);
		     if (!dir.exists()) {
		       dir.mkdirs();
		     }
		     String fileName = System.currentTimeMillis() + "." + fileType;
		     File file = new File(abPath + File.separator + mytimepath + File.separator + fileName);
		     OutputStream out;
		     out = new FileOutputStream(file);
		     InputStream in = upFile.getInputStream();
		     int readed = 0;
		     byte[] buffer = new byte[1024];
		     while ((readed = in.read(buffer, 0, 1024)) != -1) {
		       out.write(buffer, 0, readed);
		     }
		     if (out != null) out.close();
		     if (in != null) in.close();
		     return baseFolder+File.separator + mytimepath +File.separator + fileName;
		}
		return null;
	}
public static void delete(File file){
<span style="white-space:pre">		</span>if(!file.exists())return;
<span style="white-space:pre">		</span>if(file.isFile())file.delete();
<span style="white-space:pre">		</span>else if(file.isDirectory())
<span style="white-space:pre">			</span>try {
<span style="white-space:pre">				</span>deleteDirectory(file);
<span style="white-space:pre">			</span>} catch (IOException e) {
<span style="white-space:pre">				</span>e.printStackTrace();
<span style="white-space:pre">			</span>}
<span style="white-space:pre">	</span>}



   方法二:


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

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

[java]  view plain copy
  1. <bean id="multipartResolver"  
  2.     class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  
  3.     p:defaultEncoding="UTF-8" />  


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

[java]  view plain copy
  1. <beans default-lazy-init="true"  
  2.     xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:p="http://www.springframework.org/schema/p"  
  4.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.     xsi:schemaLocation="    
  8.        http://www.springframework.org/schema/beans     
  9.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  10.        http://www.springframework.org/schema/mvc     
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd     
  12.        http://www.springframework.org/schema/context    
  13.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  

        (3) 添加工具类FileOperateUtil.java

[java]  view plain copy
  1.  
  2. package com.geloin.spring.util;  
  3.   
  4. import java.io.BufferedInputStream;  
  5. import java.io.BufferedOutputStream;  
  6. import java.io.File;  
  7. import java.io.FileInputStream;  
  8. import java.io.FileOutputStream;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.ArrayList;  
  11. import java.util.Date;  
  12. import java.util.HashMap;  
  13. import java.util.Iterator;  
  14. import java.util.List;  
  15. import java.util.Map;  
  16.   
  17. import javax.servlet.http.HttpServletRequest;  
  18. import javax.servlet.http.HttpServletResponse;  
  19.   
  20. import org.apache.tools.zip.ZipEntry;  
  21. import org.apache.tools.zip.ZipOutputStream;  
  22. import org.springframework.util.FileCopyUtils;  
  23. import org.springframework.web.multipart.MultipartFile;  
  24. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  25.  
  26. public class FileOperateUtil {  
  27.     private static final String REALNAME = "realName";  
  28.     private static final String STORENAME = "storeName";  
  29.     private static final String SIZE = "size";  
  30.     private static final String SUFFIX = "suffix";  
  31.     private static final String CONTENTTYPE = "contentType";  
  32.     private static final String CREATETIME = "createTime";  
  33.     private static final String UPLOADDIR = "uploadDir/";  
  34.   
  35.    
  36.      * 将上传的文件进行重命名 
  37.     
  38.     private static String rename(String name) {  
  39.   
  40.         Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")  
  41.                 .format(new Date()));  
  42.         Long random = (long) (Math.random() * now);  
  43.         String fileName = now + "" + random;  
  44.   
  45.         if (name.indexOf(".") != -1) {  
  46.             fileName += name.substring(name.lastIndexOf("."));  
  47.         }  
  48.   
  49.         return fileName;  
  50.     }  
  51.   
  52.      
  53.      * 压缩后的文件名 
  54.    
  55.     private static String zipName(String name) {  
  56.         String prefix = "";  
  57.         if (name.indexOf(".") != -1) {  
  58.             prefix = name.substring(0, name.lastIndexOf("."));  
  59.         } else {  
  60.             prefix = name;  
  61.         }  
  62.         return prefix + ".zip";  
  63.     }  
  64.   
  65.     
  66.      * 上传文件 
  67.     
  68.     public static List<Map<String, Object>> upload(HttpServletRequest request,  
  69.             String[] params, Map<String, Object[]> values) throws Exception {  
  70.   
  71.         List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();  
  72.   
  73.         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
  74.         Map<String, MultipartFile> fileMap = mRequest.getFileMap();  
  75.   
  76.         String uploadDir = request.getSession().getServletContext()  
  77.                 .getRealPath("/")  
  78.                 + FileOperateUtil.UPLOADDIR;  
  79.         File file = new File(uploadDir);  
  80.   
  81.         if (!file.exists()) {  
  82.             file.mkdir();  
  83.         }  
  84.   
  85.         String fileName = null;  
  86.         int i = 0;  
  87.         for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()  
  88.                 .iterator(); it.hasNext(); i++) {  
  89.   
  90.             Map.Entry<String, MultipartFile> entry = it.next();  
  91.             MultipartFile mFile = entry.getValue();  
  92.   
  93.             fileName = mFile.getOriginalFilename();  
  94.   
  95.             String storeName = rename(fileName);  
  96.   
  97.             String noZipName = uploadDir + storeName;  
  98.             String zipName = zipName(noZipName);  
  99.   
  100.             // 上传成为压缩文件  
  101.             ZipOutputStream outputStream = new ZipOutputStream(  
  102.                     new BufferedOutputStream(new FileOutputStream(zipName)));  
  103.             outputStream.putNextEntry(new ZipEntry(fileName));  
  104.             outputStream.setEncoding("GBK");  
  105.   
  106.             FileCopyUtils.copy(mFile.getInputStream(), outputStream);  
  107.   
  108.             Map<String, Object> map = new HashMap<String, Object>();  
  109.             // 固定参数值对  
  110.             map.put(FileOperateUtil.REALNAME, zipName(fileName));  
  111.             map.put(FileOperateUtil.STORENAME, zipName(storeName));  
  112.             map.put(FileOperateUtil.SIZE, new File(zipName).length());  
  113.             map.put(FileOperateUtil.SUFFIX, "zip");  
  114.             map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");  
  115.             map.put(FileOperateUtil.CREATETIME, new Date());  
  116.   
  117.             // 自定义参数值对  
  118.             for (String param : params) {  
  119.                 map.put(param, values.get(param)[i]);  
  120.             }  
  121.   
  122.             result.add(map);  
  123.         }  
  124.         return result;  
  125.     }  
  126.   
  127.    
  128.      * 下载 
  129.   
  130.     public static void download(HttpServletRequest request,  
  131.             HttpServletResponse response, String storeName, String contentType,  
  132.             String realName) throws Exception {  
  133.         response.setContentType("text/html;charset=UTF-8");  
  134.         request.setCharacterEncoding("UTF-8");  
  135.         BufferedInputStream bis = null;  
  136.         BufferedOutputStream bos = null;  
  137.   
  138.         String ctxPath = request.getSession().getServletContext()  
  139.                 .getRealPath("/")  
  140.                 + FileOperateUtil.UPLOADDIR;  
  141.         String downLoadPath = ctxPath + storeName;  
  142.   
  143.         long fileLength = new File(downLoadPath).length();  
  144.   
  145.         response.setContentType(contentType);  
  146.         response.setHeader("Content-disposition""attachment; filename="  
  147.                 + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
  148.         response.setHeader("Content-Length", String.valueOf(fileLength));  
  149.   
  150.         bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
  151.         bos = new BufferedOutputStream(response.getOutputStream());  
  152.         byte[] buff = new byte[2048];  
  153.         int bytesRead;  
  154.         while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  155.             bos.write(buff, 0, bytesRead);  
  156.         }  
  157.         bis.close();  
  158.         bos.close();  
  159.     }  
  160. }  

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

        (4) 添加FileOperateController.java

[java]  view plain copy
  1.  
  2. package com.geloin.spring.controller;  
  3.   
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.ServletRequestUtils;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.geloin.spring.util.FileOperateUtil;  
  17.   

  18. @Controller  
  19. @RequestMapping(value = "background/fileOperate")  
  20. public class FileOperateController {  
  21.   
  22.      * 到上传文件的位置 
  23.  
  24.     @RequestMapping(value = "to_upload")  
  25.     public ModelAndView toUpload() {  
  26.         return new ModelAndView("background/fileOperate/upload");  
  27.     }  
  28.   
  29.    
  30.      * 上传文件 
  31.   
  32.     @RequestMapping(value = "upload")  
  33.     public ModelAndView upload(HttpServletRequest request) throws Exception {  
  34.   
  35.         Map<String, Object> map = new HashMap<String, Object>();  
  36.   
  37.         // 别名  
  38.         String[] alaises = ServletRequestUtils.getStringParameters(request,  
  39.                 "alais");  
  40.   
  41.         String[] params = new String[] { "alais" };  
  42.         Map<String, Object[]> values = new HashMap<String, Object[]>();  
  43.         values.put("alais", alaises);  
  44.   
  45.         List<Map<String, Object>> result = FileOperateUtil.upload(request,  
  46.                 params, values);  
  47.   
  48.         map.put("result", result);  
  49.   
  50.         return new ModelAndView("background/fileOperate/list", map);  
  51.     }  
  52.   
  53.  
  54.     @RequestMapping(value = "download")  
  55.     public ModelAndView download(HttpServletRequest request,  
  56.             HttpServletResponse response) throws Exception {  
  57.   
  58.         String storeName = "201205051340364510870879724.zip";  
  59.         String realName = "Java设计模式.zip";  
  60.         String contentType = "application/octet-stream";  
  61.   
  62.         FileOperateUtil.download(request, response, storeName, contentType,  
  63.                 realName);  
  64.   
  65.         return null;  
  66.     }  
  67. }  




        (5) 添加fileOperate/upload.html
<!DOCTYPE html>
  1. <html>
    <head>
    <title>upload.html</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Xenon Boostrap Admin Panel" />
    <meta name="author" content="" />
    </head>
    <body>
    <form enctype="multipart/form-data"  action="upload" method="post">
    <input type="file" name="file1" /> <input type="text" name="alais" /><br />
    <input type="submit" value="上传" />
    </form>
    </body>
    </html>  

    


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值