`

文件上传和下载

 
阅读更多

package com.framework.common.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;

/**
 * <pre>
 * Copy right information:
 * Project:gene
 * File Name:FileOperateUtil.java
 * JDK version used:
 * Commends:
 *
 *
 * Modification history    :
 * date            ver.    author            what is modified
 * ---------    ----    ---------    ---------------------------
 * 2013-12-14        1.0        Administrator         new
 * </pre>
 *
 * @author Administrator
 * @version 1.0
 */
public class FileUploadUtil {

    /**
     * 文件真实名称
     */
    public static final String REALNAME = "realName";
    /**
     * 文件修改后名称
     */
    public static final String STORENAME = "storeName";
    /**
     *  文件大小
     */
    public static final String SIZE = "size";
    /**
     *  文件后缀
     */
    public static final String SUFFIX = "suffix";
    /**
     *  文件的mimeType
     */
    public static final String CONTENTTYPE = "contentType";
    /**
     *  创建时间
     */
    public static final String CREATETIME = "createTime";
    /**
     * 文件路径
     */
    public static final String FILEPATH = "filePath";
     /**
      * 将上传的文件进行重命名  
      *
      * make by Administrator on 2013-12-14 上午10:59:54
      * @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; 
    }
   
    /**
     * 获得日期yyyyMMddHHmmss随机名称
     *
     * make by Administrator on 2014-4-15 上午10:43:30
     * @return
     */
    public static String rename() { 
         
        Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss") 
                .format(new Date())); 
        Long random = (long) (Math.random() * now); 
        String fileName = now + "" + random;   
        return fileName; 
    }
   
   
    /**
     * 压缩后的文件名
     * demo.xml = demo.zip
     * make by Administrator on 2013-12-14 上午10:59:46
     * @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"; 
    }
   
    /**
     * 获得文件后缀
     *
     * make by Administrator on 2013-12-14 下午02:14:01
     * @param path
     * @return
     */
    private static String suffixName(String path){
        String suffix = "";
        if(path.lastIndexOf(".")!= -1){
            suffix = path.substring(path.lastIndexOf(".")+1, path.length());
        }
        return suffix;
    }
   
   
    /**
     * * 上传单个文件
     *
     * make by Administrator on 2013-12-14 下午03:11:07
     * @param srcFile      MultipartFile
     * @param isZip        对上传文件是否进行压缩
     * @param uploadDir    上传路径
     * @return
     * @throws Exception
     */
    public static Map<String, Object> upload(MultipartFile srcFile,Boolean isZip,String uploadDir) throws Exception { 
 
        // 判断是否压缩
        boolean isBlooZip = (isZip == null ? false : isZip);

     
        File file = new File(uploadDir);

        if (!file.exists()) {
            file.mkdir();
        }

        String fileName = null;

        // 判断上传文件大小为0不上传
        if ("".equals(srcFile.getOriginalFilename()) && srcFile.getSize() == 0
                && srcFile.isEmpty() == true)
            return null;

        // 源文件名称
        fileName = srcFile.getOriginalFilename();

        // 修改后文件名称
        String storeName = rename(fileName);
        if(!uploadDir.endsWith(File.separator))
            uploadDir+=File.separator;
       
        // 文件上传路径
        String noZipName = uploadDir + storeName;

        if (isBlooZip) { // 压缩处理
            String zipName = zipName(noZipName);

            // 上传成为压缩文件
            ZipOutputStream outputStream = new ZipOutputStream(
                    new BufferedOutputStream(new FileOutputStream(zipName)));
            outputStream.putNextEntry(new ZipEntry(fileName));
            outputStream.setEncoding("utf-8");

            FileCopyUtils.copy(srcFile.getInputStream(), outputStream);
        } else { // 不压缩
            File uploadFile = new File(noZipName);
            FileCopyUtils.copy(srcFile.getBytes(), uploadFile);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        // 固定参数值对
        map.put(FileUploadUtil.REALNAME, isBlooZip ? zipName(fileName)
                : fileName);
        map.put(FileUploadUtil.STORENAME, isBlooZip ? zipName(storeName)
                : storeName);
       
        map.put(FileUploadUtil.FILEPATH, isBlooZip ? zipName(noZipName) : noZipName);
       
        map.put(FileUploadUtil.SIZE, new File(isBlooZip ? zipName(noZipName)
                : noZipName).length());
        map.put(FileUploadUtil.SUFFIX,
                suffixName(isBlooZip ? zipName(noZipName) : noZipName));
        map.put(FileUploadUtil.CONTENTTYPE, srcFile.getContentType());
        map.put(FileUploadUtil.CREATETIME, new Date());
 
        return map; 
    } 
    /**
     * * 上传文件
     *
     * make by Administrator on 2013-12-14 下午03:11:07
     * @param request      Request
     * @param isZip        对上传文件是否进行压缩
     * @param uploadDir    上传路径
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> upload(HttpServletRequest request,Boolean isZip,String uploadDir) throws Exception { 
         
        //判断是否压缩
        boolean isBlooZip = (isZip==null?false:isZip);
       
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); 
 
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; 
        Map<String, MultipartFile> fileMap = mRequest.getFileMap(); 
 
        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();
           
            //判断上传文件大小为0不上传
            if("".equals(mFile.getOriginalFilename()) && mFile.getSize()==0 && mFile.isEmpty()==true)continue;
           
            //源文件名称
            fileName = mFile.getOriginalFilename(); 
           
            //修改后文件名称
            String storeName = rename(fileName); 
           
            //文件上传路径
            String noZipName = uploadDir + storeName;
           
            if(isBlooZip){ //压缩处理
                String zipName = zipName(noZipName); 
                 
                // 上传成为压缩文件 
                ZipOutputStream outputStream = new ZipOutputStream( 
                        new BufferedOutputStream(new FileOutputStream(zipName))); 
                outputStream.putNextEntry(new ZipEntry(fileName)); 
                outputStream.setEncoding("utf-8"); 
     
                FileCopyUtils.copy(mFile.getInputStream(), outputStream);
            }else{ //不压缩
                File uploadFile = new File(noZipName);
                FileCopyUtils.copy(mFile.getBytes(), uploadFile);
            }
             
            Map<String, Object> map = new HashMap<String, Object>(); 
            // 固定参数值对 
            map.put(FileUploadUtil.REALNAME, isBlooZip?zipName(fileName):fileName); 
            map.put(FileUploadUtil.STORENAME, isBlooZip?zipName(storeName):storeName); 
            map.put(FileUploadUtil.SIZE, new File(isBlooZip?zipName(noZipName):noZipName).length()); 
            map.put(FileUploadUtil.SUFFIX, suffixName(isBlooZip?zipName(noZipName):noZipName)); 
            map.put(FileUploadUtil.CONTENTTYPE, mFile.getContentType()); 
            map.put(FileUploadUtil.CREATETIME, new Date()); 
            map.put(FileUploadUtil.FILEPATH, isBlooZip ? zipName(noZipName) : noZipName);
           
            result.add(map); 
        } 
        return result; 
    } 
    /**
     * 文件下载
     *
     * make by Administrator on 2013-12-14 上午11:03:05
     * @param request        Request
     * @param response       Response
     * @param filePath       文件修改后的名称+地址
     * @param contentType    内容类型[application/octet-stream]
     * @param realName       下载文件真实名称
     * @throws Exception
     */
    public static void download(HttpServletRequest request, 
            HttpServletResponse response, String filePath, String contentType, 
            String realName) throws Exception { 
        response.setContentType("text/html;charset=UTF-8"); 
        request.setCharacterEncoding("UTF-8"); 
        BufferedInputStream bis = null; 
        BufferedOutputStream bos = null; 
        long fileLength = new File(filePath).length(); 
 
        response.setContentType(contentType); 
        response.setHeader("Content-disposition", "attachment; filename=" 
                + new String(realName.getBytes("gb2312"), "ISO8859-1")); 
        response.setHeader("Content-Length", String.valueOf(fileLength)); 
 
        bis = new BufferedInputStream(new FileInputStream(filePath)); 
        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(); 
    } 
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics