SpringMVC 中文件的上传和下载

在参照了网上的相关代码之后,总结了一下在springmvc框架中实现文件上传和下载的实现方法。内容如下。


jar 包

  • ant.jar
  • commons-fileupload-1.3.1.jar
  • connom-io.jar

xml 配置

springmvcxml:




    
    
    
    
    
    
        
        
    
    
        
        
            104857600
        
        
           
            4096
        
    

页面

文件上传的页面:fileOperate/upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




文件上传


    
别名:
别名:
别名:

上传成功后的页面: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"%>




上传文件列表


    
        
              
                 上传文件名(压缩后): ${m.value }  
            
上传文件路径: ${m.value }
别名: ${m.value }

工具类

FileOperateUtil.java:

package com.export.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/";

    /**
     * 将上传的文件进行重命名
     * 
     * @author zhang_cq
     * @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;
    }

    /**
     * 压缩后的文件名
     * 
     * @author zhang_cq
     * @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";
    }

    /**
     * 上传文件
     * 
     * @author zhang_cq
     * @param request
     * @param params
     * @param values
     * @return
     * @throws Exception
     */
    public static List> upload(HttpServletRequest request, String[] params, Map values) throws Exception {

        List> result = new ArrayList>();

        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        // 获得上传的文件
        Map 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> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {

            Map.Entry 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 map = new HashMap();
            // 固定参数值对
            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()); // 创建日期
            map.put("path", uploadDir);
            // 自定义参数值对
            for (String param : params) {
                map.put(param, values.get(param)[i]);
            }

            result.add(map);
        }
        return result;
    }

    /**
     * 下载
     * 
     * @author zhang_cq
     * @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();
    }
}

controller

FileOperateController.java

package com.export.action;

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.export.util.FileOperateUtil;;

/**
 * 文件的上传和下载
 * 
 * @author zcq12
 *
 */
@Controller
public class FileOperateController {
    /**
     * 到上传文件的位置
     * 
     * @author geloin
     * @date 2012-3-29 下午4:01:31
     * @return
     */
    @RequestMapping(value = "/to_upload")
    public String toUpload() {
        return "fileOperate/upload";
    }

    /**
     * 上传文件
     * 
     * @author zhang_cq
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload")
    public ModelAndView upload(HttpServletRequest request) throws Exception {

        Map map = new HashMap();

        // 别名
        String[] alaises = ServletRequestUtils.getStringParameters(request, "alais");

        String[] params = new String[] { "alais" };
        Map values = new HashMap();
        values.put("alais", alaises);

        List> result = FileOperateUtil.upload(request, params, values);

        map.put("result", result);

        return new ModelAndView("fileOperate/list", map);
    }

    /**
     * 下载
     * 
     * @author zhang_cq
     * @param attachment
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "download")
    public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 下载源
        String storeName = "2017011821392011420519411922.zip";
        // 下载之后的文件名
        String realName = "myPhoto.zip";
        String contentType = "application/octet-stream";

        FileOperateUtil.download(request, response, storeName, contentType, realName);

        return null;
    }
}

至此就完成了 springmvc 中文件的上传和下载的相关功能。源码见codding

你可能感兴趣的:(SpringMVC 中文件的上传和下载)