【總結】java 后台文件上傳整理


public Map<String,String> clientUploadAttachment(Long belongId, String fileSource,
            MultipartFile file, User currentUser) {
        Map<String,String> map = new HashMap<String, String>();
        if(file==null){
//            map.put("uploadError", "uploadError");
            return null;//上傳失敗返回null
        }
        try{
            InputStream is = file.getInputStream();
            String storePath =upLoadPath+DateUtils.getYear()+"/"+DateUtils.getMonth()+"/"+DateUtils.getDay()+"/"+belongId+"/";
            String tempFileName = file.getOriginalFilename();
            
            //緩存文件類型轉換  源文件
            CommonsMultipartFile cf= (CommonsMultipartFile)file; 
            DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
            File tempOrginFile = fi.getStoreLocation();
            
            String mimeType = file.getContentType();
            int fileType = 5;// 文件類型 1:圖片  2:文檔 3:視頻 4:音頻 5.其他
            if (mimeType.startsWith("image/")) {
                fileType = 1;
            }else if(mimeType.startsWith("video")||mimeType.startsWith("mp4")){
                fileType = 3;
                storePath += "video/";
            }else if(mimeType.startsWith("mp3")){
                fileType = 4;
                storePath += "audio/";
            }else{
                storePath += "other/";
            }
            String uuid = IdGen.uuid();
            if(is != null&&StringUtils.isNotBlank(tempFileName)){
                Attachment attachment = new Attachment();
                attachment.setBelongId(belongId);
                attachment.setFileType(fileType);
                attachment.setFileName(tempFileName);
                attachment.setCreatorId(currentUser.getId());
                attachment.setCreatorName(currentUser.getLoginName());
                attachment.setFileSize(FileUtils.getFileSize(file));
                attachment.setFileSource(fileSource==null?5:Integer.parseInt(fileSource));
                
                //生成文件名
                String extendName = tempFileName.substring(tempFileName.indexOf("."));
                String fileName =uuid + extendName;
                String waterName = uuid + extendName;
                if(fileType == 1){//圖片 縮略圖 路徑
                    waterName = uuid + "_small" + extendName;
                }else if(fileType == 3){//視頻截圖 路徑
                    waterName = uuid + "_view" + extendName;
                }
                //設置臨時文件目錄
                String waterTempPath = SpringContextHolder.getRootRealPath()+"/static/temp/"+waterName;
                
                //開始上傳
                FTPUtils ftpUtils = FTPUtils.getInstance();
                attachment.setFilePath(storePath+fileName);
                attachment.setWaterPath(storePath+waterName);
                synchronized(this){
                    boolean upTemp = ftpUtils.storeFile(storePath,fileName,is);
                    if(upTemp){
                        if(fileType == 1){//圖片 縮略圖 處理並上傳
                             ImageUtil.createCompressImg(tempOrginFile,waterTempPath, 200);
                             File waterFile = new File(waterTempPath);
                             if(waterFile.exists()&&waterFile.isFile()){
                                 ftpUtils.storeFile(storePath,waterName,new FileInputStream(waterFile)); 
                                 FileUtils.deleteFile(waterTempPath);
                             }
                        }else if(fileType == 3){//視頻截圖 處理並上傳
                             //TODO://視頻截圖 處理並上傳
                        }
                        attachmentDao.saveObj(attachment);
                    }
                }
                map.put("attachmentId", String.valueOf(attachment.getId()));
                map.put("attachmentUrl", storePath+fileName);
                map.put("waterUrl", storePath+waterName);
                return map;
            }else{
                return null;//上傳失敗返回null
            }
        }catch(IOException e){
            e.printStackTrace();
            return null;//上傳失敗返回null
        }
    }
package com.bankhui.center.common.utils;

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 圖片處理Util
 */
public class ImageUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
       /* String imageUrl="C:\\Users\\Public\\Pictures\\Sample Pictures\\1.jpg"; 
        BufferedImage image = getBufferedImageByLocal(imageUrl); //使用ImageUtil獲取到圖片的高寬
        float scale = ((float)image.getWidth() )/ 200; //計算出寬壓縮到600px時,壓縮的多少倍
        int imageHeight = (int) (image.getHeight() / scale); //同樣將高也壓縮這個多倍(以免圖片失真)
        Tosmallerpic(new File(imageUrl), new File("D:\\000.jpg"), 200, imageHeight, 0.75f); //使用Tosmallerpic將圖片按照比例壓縮 
       */
    }  
    
    /**
     * 生成縮略圖
     * @param oldSrc
     * @param newSrc
     * @param width
     */
    public static void createCompressImg(File oldFile,String newSrc,Integer width){
        BufferedImage image = getBufferedImageByLocal(oldFile);
        float scale = ((float)image.getWidth() )/ width; 
        int imageHeight = (int) (image.getHeight() / scale); 
        Tosmallerpic(oldFile, new File(newSrc), width, imageHeight, 0.75f);
    }

    /** 
     * 通過圖片鏈接獲取
     * @param imgUrl 圖片地址 
     * @return  
     */  
    public static BufferedImage getBufferedImage(String imgUrl) {  
        URL url = null;  
        InputStream is = null;  
        BufferedImage img = null;  
        try {  
            url = new URL(imgUrl);  
            is = url.openStream();  
            img = ImageIO.read(is);  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
              
            try {  
                is.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return img;  
    }  
    
    /**
     * 文件
     * @param imgUrl
     * @return
     * @author liu787427876@126.com
     * @date 2014-7-20
     */
    public static BufferedImage getBufferedImageByLocal(File file) {  
        InputStream is = null;  
        BufferedImage img = null; 
        try {
               is = new FileInputStream(file);
               img = ImageIO.read(is);  
              } catch (FileNotFoundException e) {
               e.printStackTrace();
              } catch (IOException e) {
               e.printStackTrace();
              } finally {  
                   try {  
                       is.close();  
                   } catch (IOException e) {  
                       e.printStackTrace();  
                   }  
              } 
        return img;  
    }  
    
    public static BufferedImage getBufferedImageByLocal(String imgUrl) { 
         if(StringUtils.isBlank(imgUrl)){
          throw new NullPointerException("圖片路徑不能為空!");
         }
         File file = new File(imgUrl);
         return getBufferedImageByLocal(file);
    }
    
    /** 
     * 
     * @param f 圖片輸出路徑 
     * @param filelist 圖片路徑 
     * @param ext 縮略圖擴展名 
     * @param n 圖片名 
     * @param w 目標寬 
     * @param h 目標高 
     * @param per 百分比 
     */ 
    public static void  Tosmallerpic(File oldFile,File newFile,int width,int height,float quality){
            if(!newFile.getParentFile().exists()){
                 newFile.getParentFile().mkdirs();
             }
             Image src=null; 
             BufferedImage tag=null;
             FileOutputStream newimage=null;
            try { 
                 try{
                     src = javax.imageio.ImageIO.read(oldFile); //構造Image對象 
                 }catch(Exception e){ 
                     e.printStackTrace();
                     logger.info(oldFile.getName()+"圖片的ICC信息可能已經被破壞開始轉換:");
                     try { 
                          ThumbnailConvert convert=new ThumbnailConvert();
                          //convert.setCMYK_COMMAND(oldFile.getPath()); 
                          String CMYK_COMMAND = "mogrify -colorspace RGB -quality 100 file1";//轉換cmyk格式
                          convert.exeCommand(CMYK_COMMAND.replace("file1",oldFile.getPath()));
                          src = Toolkit.getDefaultToolkit().getImage(oldFile.getPath());
                          MediaTracker mediaTracker = new MediaTracker(new Container());
                          mediaTracker.addImage(src, 0); 
                          mediaTracker.waitForID(0); 
                          src.getWidth(null); 
                          src.getHeight(null); 
                        }catch (Exception e1){ 
                            e1.printStackTrace(); 
                        } 
                 } 
                 
               //,String ext 保留字段 縮略圖拼接字段
               //String img_midname=newFile; 
               int old_w=src.getWidth(null)==-1?width:src.getWidth(null); //得到源圖寬
               int old_h=src.getHeight(null)==-1?height:src.getHeight(null); 
               int new_w=0; 
               int new_h=0; //得到源圖長
               double w2=(old_w*1.00)/(width*1.00); 
               double h2=(old_h*1.00)/(height*1.00);
                //圖片調整為方形結束 
               if(old_w>width) 
               new_w=(int)Math.round(old_w/w2); 
               else 
                   new_w=old_w; 
               if(old_h>height) 
               new_h=(int)Math.round(old_h/h2);//計算新圖長寬 
               else 
                   new_h=old_h; 
               tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);      
               //tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //繪制縮小后的圖
               tag.getGraphics().drawImage(src.getScaledInstance(new_w, new_h,Image.SCALE_SMOOTH), 0,0,null);
               newimage=new FileOutputStream(newFile); //輸出到文件流 
               JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
               JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(tag); 
                /* 壓縮質量 */ 
               jep.setQuality(quality, true); 
               encoder.encode(tag, jep); 
               //encoder.encode(tag); //近JPEG編碼 
               newimage.close(); 
            } catch (IOException ex) { 
                 ex.printStackTrace();
                 logger.info(oldFile.getName()+"圖片壓縮問題;"+ex);
                //Logger.getLogger(File:mpress.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                if(newimage!=null){
                    try {
                        newimage.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(tag!=null){
                    tag.flush();
                }
            }
    } 

    /**
     * 縮放圖像 
     * @param srcImageFile 源圖像文件地址 
     * @param result       縮放后的圖像地址 
     * @param destWidth    縮放寬度
     * @param destHeight   縮放高度; 
     */  
    public static boolean scaleImg(File srcImageFile, String result, int destWidth, int destHeight) {  
        boolean exeRs = false;
        try{  
            BufferedImage src = ImageIO.read(srcImageFile);
            Image image = src.getScaledInstance(destWidth, destHeight, Image.SCALE_DEFAULT);  
            BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);  
            Graphics g = tag.getGraphics();  
            g.drawImage(image, 0, 0, null); // 繪制縮小后的圖  
            g.dispose();  
            ImageIO.write(tag, "JPEG", new File(result));// 輸出到文件流  
            exeRs = true;
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        return exeRs;
    }
}
package com.bankhui.core.base.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 圖片處理類
 * @author wangjx
 */
public class ImageUtils {
    private final static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    // 水印透明度 
    private static float alpha = 0.5f;
    // 水印橫向位置
    private static int positionWidth = 150;
    // 水印縱向位置
    private static int positionHeight = 300;
    // 水印文字字體
    private static Font font = new Font("宋體", Font.BOLD, 30);
    // 水印文字顏色
    private static Color color = Color.red;

    /**  
     * 給圖片添加圖片水印
     * @param iconPath 水印圖片路徑  
     * @param file 源文件  
     * @param targerPath 目標圖片路徑  
     * @param degree 水印圖片旋轉角度  
     */  
    public static void markImageByIcon(String iconPath, File file,   
            String targerPath, Integer degree) {   
        OutputStream os = null;   
        try { 
            logger.info("水印圖片路徑:{}", iconPath);
            logger.info("源文件:{}", file.getAbsolutePath());
            logger.info("目標圖片路徑:{}", targerPath);
            Image srcImg = ImageIO.read(file);  
  
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),   
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);   
  
            // 得到畫筆對象   
            Graphics2D g = buffImg.createGraphics();   
  
            // 設置對線段的鋸齒狀邊緣處理   
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,   
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);   
  
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg   
                    .getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);   
  
            if (null != degree) {   
                // 設置水印旋轉   
                g.rotate(Math.toRadians(degree),   
                        (double) buffImg.getWidth() / 2, (double) buffImg   
                                .getHeight() / 2);   
            }   
  
            // 水印圖象的路徑 水印一般為gif或者png的,這樣可設置透明度   
            ImageIcon imgIcon = new ImageIcon(iconPath);   
  
            // 得到Image對象。   
            Image img = imgIcon.getImage();   
  
            float alpha = 0.5f; // 透明度   
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,   
                    alpha));   
  
            // 表示水印圖片的位置   相對於中心店的寬高以及水印圖片寬高(img,x,y,width,height,obnull)
            g.drawImage(img, buffImg.getWidth() / 6,buffImg.getHeight() / 3, buffImg.getWidth() / 2,buffImg.getHeight() / 4, null);   
  
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));   
  
            g.dispose();   
  
            os = new FileOutputStream(targerPath);   
  
            // 生成圖片   
            ImageIO.write(buffImg, "JPG", os);   
  
            logger.info("圖片完成添加水印");   
        } catch (Exception e) {   
            e.printStackTrace(); 
            logger.error("圖片完成添加水印error:{}", e.getMessage());
        } finally {   
            try {   
                if (null != os)   
                    os.close();   
            } catch (Exception e) {   
                e.printStackTrace();   
            }   
        }   
    }   
    
    /**
     * 給圖片添加水印文字
     * @param logoText 水印文字
     * @param srcImgPath 原圖片路徑
     * @param targerPath 目標圖片路徑
     * @param degree 旋轉角度
     */
    public static void markImageByText(String logoText, String srcImgPath,
            String targerPath, Integer degree) {
         
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源圖片
            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
 
            // 2、得到畫筆對象
            Graphics2D g = buffImg.createGraphics();
            // 3、設置對線段的鋸齒狀邊緣處理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 4、設置水印旋轉
            if (null != degree) {
                g.rotate(Math.toRadians(degree),(double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            // 5、設置水印文字顏色
            g.setColor(color);
            // 6、設置水印文字Font
            g.setFont(font);
            // 7、設置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
            // 8、第一參數->設置的內容,后面兩個參數->文字在圖片上的坐標位置(x,y)
            g.drawString(logoText, positionWidth, positionHeight);
            // 9、釋放資源
            g.dispose();
            // 10、生成圖片
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg, "JPG", os);
 
            logger.info("圖片完成添加水印文字");
             
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 判斷文件是不是圖片
     * @param file
     * @return
     * @author guogf
     */
    public static boolean isImage(File file)  
        {  
            boolean flag = false;   
            try  
            {  
                Image is = ImageIO.read(file);  
                if(null != is)  
                {  
                    flag = true;
                }
            } catch (Exception e)  
            {  
                e.printStackTrace();  
            }  
            return flag;  
        }
    
    public static void main(String[] args) {
        markImageByText("測試", "d:/5442.jpg", "d:/zzz.jpg", 45);
//        markImageByIcon("d:/logo.png", "d:/5442.jpg", "d:/zzz.jpg", 45);
        
    }
    
}
/**
     * 用戶附件上傳
     */
    @Override
//    @Transactional
    public Result uploadAttachment(Attachment attachment,
            MultipartFile[] files) {
    Result result = new Result();
    for (MultipartFile file: files) {
        try {
            if(file!=null){
                InputStream is = file.getInputStream();
                String tempFileName = file.getOriginalFilename();
                String fileType = file.getContentType();
                boolean isImage = fileType.contains("image/");
                if(is != null&&StringUtils.isNotBlank(tempFileName)){
                    //生成文件名
                    String uuid = IdGen.uuid();
                    String fileName = uuid+tempFileName.substring(tempFileName.indexOf("."));
                    String waterName= uuid + "_water"+tempFileName.substring(tempFileName.indexOf("."));
                    //生成文件路徑
                    String storePath = upLoadPath+attachment.getBelongId()+"/";
                    
                    //緩存文件類型轉換
                    CommonsMultipartFile cf= (CommonsMultipartFile)file; 
                    DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
                    File tempFile = fi.getStoreLocation();

                    boolean ftpWaterRs=true;
                    FTPUtils ftpUtils = FTPUtils.getInstance();
                    //圖片加水印 getResourceRootRealPath
                    if(isImage){
                        attachment.setFileType(1);

                        String waterTempPath = SpringContextHolder.getRootRealPath()+"/"+waterName;

                        String logoPath=SpringContextHolder.getRootRealPath()+"/Contents/bankhimages/shuiyin.png";  

                           ImageUtils.markImageByIcon(logoPath, tempFile, waterTempPath, 45);
                        File waterFile = new File(waterTempPath);
                        //上傳水印圖片
                        ftpWaterRs = ftpUtils.storeFile(storePath,waterName,new FileInputStream(waterFile));
                        if(!ftpWaterRs){
                            is.close();
                            result.setCode(GlobalConstant.FAIL);
                            result.setMsg("圖片添加水印失敗,請重試······");
                            return result;
                        }
                        FileUtils.deleteFile(waterTempPath);
                        
                        attachment.setWaterPath(storePath+waterName);
                    }else{
                        attachment.setFileType(2);
                        attachment.setWaterPath(storePath+fileName);
                    }
                    
                    //上傳源文件
                    boolean ftpFileRs = ftpUtils.storeFile(storePath, fileName, is);
                    if(ftpFileRs&&ftpWaterRs){
                        //更新舊文件記錄
/*                        Map map= new HashMap<String, String >();
                        map.put("type", attachment.getType());
                        map.put("userId", attachment.getUserId());
                        map.put("status", 0);//標記為歷史記錄
                        homeUserInfoManager.updateAttachmentRecord(map);*/
                        //添加新的文件記錄
                        attachment.setFilePath(storePath+fileName);
                        //attachment.setIsWater(0);
                        attachment.setStatus(1);
                        int rs=homeUserInfoManager.addAttachmentRecord(attachment);
                        if(rs>0){
                            result.setCode(GlobalConstant.SUCCESS);
                            result.setMsg("附件上傳成功。");
                        }else{
                            result.setCode(GlobalConstant.FAIL);
                            result.setMsg("附件記錄保存失敗了···請重試······");
                        }
                    }else{
                        result.setCode(GlobalConstant.FAIL);
                        result.setMsg("上傳附件失敗了···請重試······");
                    }
                    is.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}
/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.bankhui.center.common.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;

/**
 * 文件操作工具類
 * 實現文件的創建、刪除、復制、壓縮、解壓以及目錄的創建、刪除、復制、壓縮解壓等功能
 * @author ThinkGem
 * @version 2015-3-16
 */
public class FileUtils extends org.apache.commons.io.FileUtils {
    
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 復制單個文件,如果目標文件存在,則不覆蓋
     * @param srcFileName 待復制的文件名
     * @param descFileName 目標文件名
     * @return 如果復制成功,則返回true,否則返回false
     */
    public static boolean copyFile(String srcFileName, String descFileName) {
        return FileUtils.copyFileCover(srcFileName, descFileName, false);
    }

    /**
     * 復制單個文件
     * @param srcFileName 待復制的文件名
     * @param descFileName 目標文件名
     * @param coverlay 如果目標文件已存在,是否覆蓋
     * @return 如果復制成功,則返回true,否則返回false
     */
    public static boolean copyFileCover(String srcFileName,
            String descFileName, boolean coverlay) {
        File srcFile = new File(srcFileName);
        // 判斷源文件是否存在
        if (!srcFile.exists()) {
            logger.debug("復制文件失敗,源文件 " + srcFileName + " 不存在!");
            return false;
        }
        // 判斷源文件是否是合法的文件
        else if (!srcFile.isFile()) {
            logger.debug("復制文件失敗," + srcFileName + " 不是一個文件!");
            return false;
        }
        File descFile = new File(descFileName);
        // 判斷目標文件是否存在
        if (descFile.exists()) {
            // 如果目標文件存在,並且允許覆蓋
            if (coverlay) {
                logger.debug("目標文件已存在,准備刪除!");
                if (!FileUtils.delFile(descFileName)) {
                    logger.debug("刪除目標文件 " + descFileName + " 失敗!");
                    return false;
                }
            } else {
                logger.debug("復制文件失敗,目標文件 " + descFileName + " 已存在!");
                return false;
            }
        } else {
            if (!descFile.getParentFile().exists()) {
                // 如果目標文件所在的目錄不存在,則創建目錄
                logger.debug("目標文件所在的目錄不存在,創建目錄!");
                // 創建目標文件所在的目錄
                if (!descFile.getParentFile().mkdirs()) {
                    logger.debug("創建目標文件所在的目錄失敗!");
                    return false;
                }
            }
        }

        // 准備復制文件
        // 讀取的位數
        int readByte = 0;
        InputStream ins = null;
        OutputStream outs = null;
        try {
            // 打開源文件
            ins = new FileInputStream(srcFile);
            // 打開目標文件的輸出流
            outs = new FileOutputStream(descFile);
            byte[] buf = new byte[1024];
            // 一次讀取1024個字節,當readByte為-1時表示文件已經讀取完畢
            while ((readByte = ins.read(buf)) != -1) {
                // 將讀取的字節流寫入到輸出流
                outs.write(buf, 0, readByte);
            }
            logger.debug("復制單個文件 " + srcFileName + " 到" + descFileName
                    + "成功!");
            return true;
        } catch (Exception e) {
            logger.debug("復制文件失敗:" + e.getMessage());
            return false;
        } finally {
            // 關閉輸入輸出流,首先關閉輸出流,然后再關閉輸入流
            if (outs != null) {
                try {
                    outs.close();
                } catch (IOException oute) {
                    oute.printStackTrace();
                }
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException ine) {
                    ine.printStackTrace();
                }
            }
        }
    }

    /**
     * 復制整個目錄的內容,如果目標目錄存在,則不覆蓋
     * @param srcDirName 源目錄名
     * @param descDirName 目標目錄名
     * @return 如果復制成功返回true,否則返回false
     */
    public static boolean copyDirectory(String srcDirName, String descDirName) {
        return FileUtils.copyDirectoryCover(srcDirName, descDirName,
                false);
    }

    /**
     * 復制整個目錄的內容 
     * @param srcDirName 源目錄名
     * @param descDirName 目標目錄名
     * @param coverlay 如果目標目錄存在,是否覆蓋
     * @return 如果復制成功返回true,否則返回false
     */
    public static boolean copyDirectoryCover(String srcDirName,
            String descDirName, boolean coverlay) {
        File srcDir = new File(srcDirName);
        // 判斷源目錄是否存在
        if (!srcDir.exists()) {
            logger.debug("復制目錄失敗,源目錄 " + srcDirName + " 不存在!");
            return false;
        }
        // 判斷源目錄是否是目錄
        else if (!srcDir.isDirectory()) {
            logger.debug("復制目錄失敗," + srcDirName + " 不是一個目錄!");
            return false;
        }
        // 如果目標文件夾名不以文件分隔符結尾,自動添加文件分隔符
        String descDirNames = descDirName;
        if (!descDirNames.endsWith(File.separator)) {
            descDirNames = descDirNames + File.separator;
        }
        File descDir = new File(descDirNames);
        // 如果目標文件夾存在
        if (descDir.exists()) {
            if (coverlay) {
                // 允許覆蓋目標目錄
                logger.debug("目標目錄已存在,准備刪除!");
                if (!FileUtils.delFile(descDirNames)) {
                    logger.debug("刪除目錄 " + descDirNames + " 失敗!");
                    return false;
                }
            } else {
                logger.debug("目標目錄復制失敗,目標目錄 " + descDirNames + " 已存在!");
                return false;
            }
        } else {
            // 創建目標目錄
            logger.debug("目標目錄不存在,准備創建!");
            if (!descDir.mkdirs()) {
                logger.debug("創建目標目錄失敗!");
                return false;
            }

        }

        boolean flag = true;
        // 列出源目錄下的所有文件名和子目錄名
        File[] files = srcDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 如果是一個單個文件,則直接復制
            if (files[i].isFile()) {
                flag = FileUtils.copyFile(files[i].getAbsolutePath(),
                        descDirNames + files[i].getName());
                // 如果拷貝文件失敗,則退出循環
                if (!flag) {
                    break;
                }
            }
            // 如果是子目錄,則繼續復制目錄
            if (files[i].isDirectory()) {
                flag = FileUtils.copyDirectory(files[i]
                        .getAbsolutePath(), descDirNames + files[i].getName());
                // 如果拷貝目錄失敗,則退出循環
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            logger.debug("復制目錄 " + srcDirName + " 到 " + descDirName + " 失敗!");
            return false;
        }
        logger.debug("復制目錄 " + srcDirName + " 到 " + descDirName + " 成功!");
        return true;

    }

    /**
     * 
     * 刪除文件,可以刪除單個文件或文件夾
     * 
     * @param fileName 被刪除的文件名
     * @return 如果刪除成功,則返回true,否是返回false
     */
    public static boolean delFile(String fileName) {
         File file = new File(fileName);
        if (!file.exists()) {
            logger.debug(fileName + " 文件不存在!");
            return true;
        } else {
            if (file.isFile()) {
                return FileUtils.deleteFile(fileName);
            } else {
                return FileUtils.deleteDirectory(fileName);
            }
        }
    }

    /**
     * 
     * 刪除單個文件
     * 
     * @param fileName 被刪除的文件名
     * @return 如果刪除成功,則返回true,否則返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                logger.debug("刪除文件 " + fileName + " 成功!");
                return true;
            } else {
                logger.debug("刪除文件 " + fileName + " 失敗!");
                return false;
            }
        } else {
            logger.debug(fileName + " 文件不存在!");
            return true;
        }
    }

    /**
     * 
     * 刪除目錄及目錄下的文件
     * 
     * @param dirName 被刪除的目錄所在的文件路徑
     * @return 如果目錄刪除成功,則返回true,否則返回false
     */
    public static boolean deleteDirectory(String dirName) {
        String dirNames = dirName;
        if (!dirNames.endsWith(File.separator)) {
            dirNames = dirNames + File.separator;
        }
        File dirFile = new File(dirNames);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            logger.debug(dirNames + " 目錄不存在!");
            return true;
        }
        boolean flag = true;
        // 列出全部文件及子目錄
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 刪除子文件
            if (files[i].isFile()) {
                flag = FileUtils.deleteFile(files[i].getAbsolutePath());
                // 如果刪除文件失敗,則退出循環
                if (!flag) {
                    break;
                }
            }
            // 刪除子目錄
            else if (files[i].isDirectory()) {
                flag = FileUtils.deleteDirectory(files[i]
                        .getAbsolutePath());
                // 如果刪除子目錄失敗,則退出循環
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            logger.debug("刪除目錄失敗!");
            return false;
        }
        // 刪除當前目錄
        if (dirFile.delete()) {
            logger.debug("刪除目錄 " + dirName + " 成功!");
            return true;
        } else {
            logger.debug("刪除目錄 " + dirName + " 失敗!");
            return false;
        }

    }

    /**
     * 創建單個文件
     * @param descFileName 文件名,包含路徑
     * @return 如果創建成功,則返回true,否則返回false
     */
    public static boolean createFile(String descFileName) {
        File file = new File(descFileName);
        if (file.exists()) {
            logger.debug("文件 " + descFileName + " 已存在!");
            return false;
        }
        if (descFileName.endsWith(File.separator)) {
            logger.debug(descFileName + " 為目錄,不能創建目錄!");
            return false;
        }
        if (!file.getParentFile().exists()) {
            // 如果文件所在的目錄不存在,則創建目錄
            if (!file.getParentFile().mkdirs()) {
                logger.debug("創建文件所在的目錄失敗!");
                return false;
            }
        }

        // 創建文件
        try {
            if (file.createNewFile()) {
                logger.debug(descFileName + " 文件創建成功!");
                return true;
            } else {
                logger.debug(descFileName + " 文件創建失敗!");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(descFileName + " 文件創建失敗!");
            return false;
        }

    }

    /**
     * 創建目錄
     * @param descDirName 目錄名,包含路徑
     * @return 如果創建成功,則返回true,否則返回false
     */
    public static boolean createDirectory(String descDirName) {
        String descDirNames = descDirName;
        if (!descDirNames.endsWith(File.separator)) {
            descDirNames = descDirNames + File.separator;
        }
        File descDir = new File(descDirNames);
        if (descDir.exists()) {
            logger.debug("目錄 " + descDirNames + " 已存在!");
            return false;
        }
        // 創建目錄
        if (descDir.mkdirs()) {
            logger.debug("目錄 " + descDirNames + " 創建成功!");
            return true;
        } else {
            logger.debug("目錄 " + descDirNames + " 創建失敗!");
            return false;
        }

    }

    /**
     * 寫入文件
     * @param file 要寫入的文件
     */
    public static void writeToFile(String fileName, String content, boolean append) {
        try {
            FileUtils.write(new File(fileName), content, "utf-8", append);
            logger.debug("文件 " + fileName + " 寫入成功!");
        } catch (IOException e) {
            logger.debug("文件 " + fileName + " 寫入失敗! " + e.getMessage());
        }
    }

    /**
     * 寫入文件
     * @param file 要寫入的文件
     */
    public static void writeToFile(String fileName, String content, String encoding, boolean append) {
        try {
            FileUtils.write(new File(fileName), content, encoding, append);
            logger.debug("文件 " + fileName + " 寫入成功!");
        } catch (IOException e) {
            logger.debug("文件 " + fileName + " 寫入失敗! " + e.getMessage());
        }
    }
    
    /**
     * 壓縮文件或目錄
     * @param srcDirName 壓縮的根目錄
     * @param fileName 根目錄下的待壓縮的文件名或文件夾名,其中*或""表示跟目錄下的全部文件
     * @param descFileName 目標zip文件
     */
    public static void zipFiles(String srcDirName, String fileName,
            String descFileName) {
        // 判斷目錄是否存在
        if (srcDirName == null) {
            logger.debug("文件壓縮失敗,目錄 " + srcDirName + " 不存在!");
            return;
        }
        File fileDir = new File(srcDirName);
        if (!fileDir.exists() || !fileDir.isDirectory()) {
            logger.debug("文件壓縮失敗,目錄 " + srcDirName + " 不存在!");
            return;
        }
        String dirPath = fileDir.getAbsolutePath();
        File descFile = new File(descFileName);
        try {
            ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(
                    descFile));
            if ("*".equals(fileName) || "".equals(fileName)) {
                FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
            } else {
                File file = new File(fileDir, fileName);
                if (file.isFile()) {
                    FileUtils.zipFilesToZipFile(dirPath, file, zouts);
                } else {
                    FileUtils
                            .zipDirectoryToZipFile(dirPath, file, zouts);
                }
            }
            zouts.close();
            logger.debug(descFileName + " 文件壓縮成功!");
        } catch (Exception e) {
            logger.debug("文件壓縮失敗:" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 解壓縮ZIP文件,將ZIP文件里的內容解壓到descFileName目錄下
     * @param zipFileName 需要解壓的ZIP文件
     * @param descFileName 目標文件
     */
    public static boolean unZipFiles(String zipFileName, String descFileName) {
        String descFileNames = descFileName;
        if (!descFileNames.endsWith(File.separator)) {
            descFileNames = descFileNames + File.separator;
        }        
        try {
            // 根據ZIP文件創建ZipFile對象
            ZipFile zipFile = new ZipFile(zipFileName);
            ZipEntry entry = null;
            String entryName = null;
            String descFileDir = null;
            byte[] buf = new byte[4096];
            int readByte = 0;
            // 獲取ZIP文件里所有的entry
            @SuppressWarnings("rawtypes")
            Enumeration enums = zipFile.getEntries();
            // 遍歷所有entry
            while (enums.hasMoreElements()) {
                entry = (ZipEntry) enums.nextElement();
                // 獲得entry的名字
                entryName = entry.getName();
                descFileDir = descFileNames + entryName;
                if (entry.isDirectory()) {
                    // 如果entry是一個目錄,則創建目錄
                    new File(descFileDir).mkdirs();
                    continue;
                } else {
                    // 如果entry是一個文件,則創建父目錄
                    new File(descFileDir).getParentFile().mkdirs();
                }
                File file = new File(descFileDir);
                // 打開文件輸出流
                OutputStream os = new FileOutputStream(file);
                // 從ZipFile對象中打開entry的輸入流
                InputStream is = zipFile.getInputStream(entry);
                while ((readByte = is.read(buf)) != -1) {
                    os.write(buf, 0, readByte);
                }
                os.close();
                is.close();
            }
            zipFile.close();
            logger.debug("文件解壓成功!");
            return true;
        } catch (Exception e) {
            logger.debug("文件解壓失敗:" + e.getMessage());
            return false;
        }
    }

    /**
     * 將目錄壓縮到ZIP輸出流
     * @param dirPath 目錄路徑
     * @param fileDir 文件信息
     * @param zouts 輸出流
     */
    public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
        if (fileDir.isDirectory()) {
            File[] files = fileDir.listFiles();
            // 空的文件夾
            if (files.length == 0) {
                // 目錄信息
                ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
                try {
                    zouts.putNextEntry(entry);
                    zouts.closeEntry();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }

            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    // 如果是文件,則調用文件壓縮方法
                    FileUtils
                            .zipFilesToZipFile(dirPath, files[i], zouts);
                } else {
                    // 如果是目錄,則遞歸調用
                    FileUtils.zipDirectoryToZipFile(dirPath, files[i],
                            zouts);
                }
            }
        }
    }

    /**
     * 將文件壓縮到ZIP輸出流
     * @param dirPath 目錄路徑
     * @param file 文件
     * @param zouts 輸出流
     */
    public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
        FileInputStream fin = null;
        ZipEntry entry = null;
        // 創建復制緩沖區
        byte[] buf = new byte[4096];
        int readByte = 0;
        if (file.isFile()) {
            try {
                // 創建一個文件輸入流
                fin = new FileInputStream(file);
                // 創建一個ZipEntry
                entry = new ZipEntry(getEntryName(dirPath, file));
                // 存儲信息到壓縮文件
                zouts.putNextEntry(entry);
                // 復制字節到壓縮文件
                while ((readByte = fin.read(buf)) != -1) {
                    zouts.write(buf, 0, readByte);
                }
                zouts.closeEntry();
                fin.close();
                System.out
                        .println("添加文件 " + file.getAbsolutePath() + " 到zip文件中!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 獲取待壓縮文件在ZIP文件中entry的名字,即相對於跟目錄的相對路徑名
     * @param dirPat 目錄名
     * @param file entry文件名
     * @return
     */
    private static String getEntryName(String dirPath, File file) {
        String dirPaths = dirPath;
        if (!dirPaths.endsWith(File.separator)) {
            dirPaths = dirPaths + File.separator;
        }
        String filePath = file.getAbsolutePath();
        // 對於目錄,必須在entry名字后面加上"/",表示它將以目錄項存儲
        if (file.isDirectory()) {
            filePath += "/";
        }
        int index = filePath.indexOf(dirPaths);

        return filePath.substring(index + dirPaths.length());
    }

    /**
     * 根據“文件名的后綴”獲取文件內容類型(而非根據File.getContentType()讀取的文件類型)
     * @param returnFileName 帶驗證的文件名
     * @return 返回文件類型
     */
    public static String getContentType(String returnFileName) {
        String contentType = "application/octet-stream";
        if (returnFileName.lastIndexOf(".") < 0)
            return contentType;
        returnFileName = returnFileName.toLowerCase();
        returnFileName = returnFileName.substring(returnFileName.lastIndexOf(".") + 1);
        if (returnFileName.equals("html") || returnFileName.equals("htm") || returnFileName.equals("shtml")) {
            contentType = "text/html";
        } else if (returnFileName.equals("apk")) {
            contentType = "application/vnd.android.package-archive";
        } else if (returnFileName.equals("sis")) {
            contentType = "application/vnd.symbian.install";
        } else if (returnFileName.equals("sisx")) {
            contentType = "application/vnd.symbian.install";
        } else if (returnFileName.equals("exe")) {
            contentType = "application/x-msdownload";
        } else if (returnFileName.equals("msi")) {
            contentType = "application/x-msdownload";
        } else if (returnFileName.equals("css")) {
            contentType = "text/css";
        } else if (returnFileName.equals("xml")) {
            contentType = "text/xml";
        } else if (returnFileName.equals("gif")) {
            contentType = "image/gif";
        } else if (returnFileName.equals("jpeg") || returnFileName.equals("jpg")) {
            contentType = "image/jpeg";
        } else if (returnFileName.equals("js")) {
            contentType = "application/x-javascript";
        } else if (returnFileName.equals("atom")) {
            contentType = "application/atom+xml";
        } else if (returnFileName.equals("rss")) {
            contentType = "application/rss+xml";
        } else if (returnFileName.equals("mml")) {
            contentType = "text/mathml";
        } else if (returnFileName.equals("txt")) {
            contentType = "text/plain";
        } else if (returnFileName.equals("jad")) {
            contentType = "text/vnd.sun.j2me.app-descriptor";
        } else if (returnFileName.equals("wml")) {
            contentType = "text/vnd.wap.wml";
        } else if (returnFileName.equals("htc")) {
            contentType = "text/x-component";
        } else if (returnFileName.equals("png")) {
            contentType = "image/png";
        } else if (returnFileName.equals("tif") || returnFileName.equals("tiff")) {
            contentType = "image/tiff";
        } else if (returnFileName.equals("wbmp")) {
            contentType = "image/vnd.wap.wbmp";
        } else if (returnFileName.equals("ico")) {
            contentType = "image/x-icon";
        } else if (returnFileName.equals("jng")) {
            contentType = "image/x-jng";
        } else if (returnFileName.equals("bmp")) {
            contentType = "image/x-ms-bmp";
        } else if (returnFileName.equals("svg")) {
            contentType = "image/svg+xml";
        } else if (returnFileName.equals("jar") || returnFileName.equals("var") 
                || returnFileName.equals("ear")) {
            contentType = "application/java-archive";
        } else if (returnFileName.equals("doc")) {
            contentType = "application/msword";
        } else if (returnFileName.equals("pdf")) {
            contentType = "application/pdf";
        } else if (returnFileName.equals("rtf")) {
            contentType = "application/rtf";
        } else if (returnFileName.equals("xls")) {
            contentType = "application/vnd.ms-excel";
        } else if (returnFileName.equals("ppt")) {
            contentType = "application/vnd.ms-powerpoint";
        } else if (returnFileName.equals("7z")) {
            contentType = "application/x-7z-compressed";
        } else if (returnFileName.equals("rar")) {
            contentType = "application/x-rar-compressed";
        } else if (returnFileName.equals("swf")) {
            contentType = "application/x-shockwave-flash";
        } else if (returnFileName.equals("rpm")) {
            contentType = "application/x-redhat-package-manager";
        } else if (returnFileName.equals("der") || returnFileName.equals("pem")
                || returnFileName.equals("crt")) {
            contentType = "application/x-x509-ca-cert";
        } else if (returnFileName.equals("xhtml")) {
            contentType = "application/xhtml+xml";
        } else if (returnFileName.equals("zip")) {
            contentType = "application/zip";
        } else if (returnFileName.equals("mid") || returnFileName.equals("midi") 
                || returnFileName.equals("kar")) {
            contentType = "audio/midi";
        } else if (returnFileName.equals("mp3")) {
            contentType = "audio/mpeg";
        } else if (returnFileName.equals("ogg")) {
            contentType = "audio/ogg";
        } else if (returnFileName.equals("m4a")) {
            contentType = "audio/x-m4a";
        } else if (returnFileName.equals("ra")) {
            contentType = "audio/x-realaudio";
        } else if (returnFileName.equals("3gpp")
                || returnFileName.equals("3gp")) {
            contentType = "video/3gpp";
        } else if (returnFileName.equals("mp4")) {
            contentType = "video/mp4";
        } else if (returnFileName.equals("mpeg")
                || returnFileName.equals("mpg")) {
            contentType = "video/mpeg";
        } else if (returnFileName.equals("mov")) {
            contentType = "video/quicktime";
        } else if (returnFileName.equals("flv")) {
            contentType = "video/x-flv";
        } else if (returnFileName.equals("m4v")) {
            contentType = "video/x-m4v";
        } else if (returnFileName.equals("mng")) {
            contentType = "video/x-mng";
        } else if (returnFileName.equals("asx") || returnFileName.equals("asf")) {
            contentType = "video/x-ms-asf";
        } else if (returnFileName.equals("wmv")) {
            contentType = "video/x-ms-wmv";
        } else if (returnFileName.equals("avi")) {
            contentType = "video/x-msvideo";
        }
        return contentType;
    }
    
    /**
     * 向瀏覽器發送文件下載,支持斷點續傳
     * @param file 要下載的文件
     * @param request 請求對象
     * @param response 響應對象
     * @return 返回錯誤信息,無錯誤信息返回null
     */
    public static String downFile(File file, HttpServletRequest request, HttpServletResponse response){
         return downFile(file, request, response, null);
    }
    
    /**
     * 向瀏覽器發送文件下載,支持斷點續傳
     * @param file 要下載的文件
     * @param request 請求對象
     * @param response 響應對象
     * @param fileName 指定下載的文件名
     * @return 返回錯誤信息,無錯誤信息返回null
     */
    public static String downFile(File file, HttpServletRequest request, HttpServletResponse response, String fileName){
        String error  = null;
        if (file != null && file.exists()) {
            if (file.isFile()) {
                if (file.length() <= 0) {
                    error = "該文件是一個空文件。";
                }
                if (!file.canRead()) {
                    error = "該文件沒有讀取權限。";
                }
            } else {
                error = "該文件是一個文件夾。";
            }
        } else {
            error = "文件已丟失或不存在!";
        }
        if (error != null){
            logger.debug("---------------" + file + " " + error);
            return error;
        }

        long fileLength = file.length(); // 記錄文件大小
        long pastLength = 0;     // 記錄已下載文件大小
        int rangeSwitch = 0;     // 0:從頭開始的全文下載;1:從某字節開始的下載(bytes=27000-);2:從某字節開始到某字節結束的下載(bytes=27000-39000)
        long toLength = 0;         // 記錄客戶端需要下載的字節段的最后一個字節偏移量(比如bytes=27000-39000,則這個值是為39000)
        long contentLength = 0; // 客戶端請求的字節總量
        String rangeBytes = ""; // 記錄客戶端傳來的形如“bytes=27000-”或者“bytes=27000-39000”的內容
        RandomAccessFile raf = null; // 負責讀取數據
        OutputStream os = null;     // 寫出數據
        OutputStream out = null;     // 緩沖
        byte b[] = new byte[1024];     // 暫存容器

        if (request.getHeader("Range") != null) { // 客戶端請求的下載的文件塊的開始字節
            response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);
            logger.debug("request.getHeader(\"Range\") = " + request.getHeader("Range"));
            rangeBytes = request.getHeader("Range").replaceAll("bytes=", "");
            if (rangeBytes.indexOf('-') == rangeBytes.length() - 1) {// bytes=969998336-
                rangeSwitch = 1;
                rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                pastLength = Long.parseLong(rangeBytes.trim());
                contentLength = fileLength - pastLength; // 客戶端請求的是 969998336  之后的字節
            } else { // bytes=1275856879-1275877358
                rangeSwitch = 2;
                String temp0 = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length());
                pastLength = Long.parseLong(temp0.trim()); // bytes=1275856879-1275877358,從第 1275856879 個字節開始下載
                toLength = Long.parseLong(temp2); // bytes=1275856879-1275877358,到第 1275877358 個字節結束
                contentLength = toLength - pastLength; // 客戶端請求的是 1275856879-1275877358 之間的字節
            }
        } else { // 從開始進行下載
            contentLength = fileLength; // 客戶端要求全文下載
        }

        // 如果設設置了Content-Length,則客戶端會自動進行多線程下載。如果不希望支持多線程,則不要設置這個參數。 響應的格式是:
        // Content-Length: [文件的總大小] - [客戶端請求的下載的文件塊的開始字節]
        // ServletActionContext.getResponse().setHeader("Content- Length", new Long(file.length() - p).toString());
        response.reset(); // 告訴客戶端允許斷點續傳多線程連接下載,響應的格式是:Accept-Ranges: bytes
        if (pastLength != 0) {
            response.setHeader("Accept-Ranges", "bytes");// 如果是第一次下,還沒有斷點續傳,狀態是默認的 200,無需顯式設置;響應的格式是:HTTP/1.1 200 OK
            // 不是從最開始下載, 響應的格式是: Content-Range: bytes [文件塊的開始字節]-[文件的總大小 - 1]/[文件的總大小]
            logger.debug("---------------不是從開始進行下載!服務器即將開始斷點續傳...");
            switch (rangeSwitch) {
                case 1: { // 針對 bytes=27000- 的請求
                    String contentRange = new StringBuffer("bytes ").append(new Long(pastLength).toString()).append("-")
                            .append(new Long(fileLength - 1).toString()).append("/").append(new Long(fileLength).toString()).toString();
                    response.setHeader("Content-Range", contentRange);
                    break;
                }
                case 2: { // 針對 bytes=27000-39000 的請求
                    String contentRange = rangeBytes + "/" + new Long(fileLength).toString();
                    response.setHeader("Content-Range", contentRange);
                    break;
                }
                default: {
                    break;
                }
            }
        } else {
            // 是從開始下載
            logger.debug("---------------是從開始進行下載!");
        }

        try {
            response.addHeader("Content-Disposition", "attachment; filename=\"" + 
                    Encodes.urlEncode(StringUtils.isBlank(fileName) ? file.getName() : fileName) + "\"");
            response.setContentType(getContentType(file.getName())); // set the MIME type.
            response.addHeader("Content-Length", String.valueOf(contentLength));
            os = response.getOutputStream();
            out = new BufferedOutputStream(os);
            raf = new RandomAccessFile(file, "r");
            try {
                switch (rangeSwitch) {
                    case 0: { // 普通下載,或者從頭開始的下載 同1
                    }
                    case 1: { // 針對 bytes=27000- 的請求
                        raf.seek(pastLength); // 形如 bytes=969998336- 的客戶端請求,跳過 969998336 個字節
                        int n = 0;
                        while ((n = raf.read(b, 0, 1024)) != -1) {
                            out.write(b, 0, n);
                        }
                        break;
                    }
                    case 2: { // 針對 bytes=27000-39000 的請求
                        raf.seek(pastLength); // 形如 bytes=1275856879-1275877358 的客戶端請求,找到第 1275856879 個字節
                        int n = 0;
                        long readLength = 0; // 記錄已讀字節數
                        while (readLength <= contentLength - 1024) {// 大部分字節在這里讀取
                            n = raf.read(b, 0, 1024);
                            readLength += 1024;
                            out.write(b, 0, n);
                        }
                        if (readLength <= contentLength) { // 余下的不足 1024 個字節在這里讀取
                            n = raf.read(b, 0, (int) (contentLength - readLength));
                            out.write(b, 0, n);
                        }
                        break;
                    }
                    default: {
                        break;
                    }
                }
                out.flush();
                logger.debug("---------------下載完成!");
            } catch (IOException ie) {
                /**
                 * 在寫數據的時候, 對於 ClientAbortException 之類的異常,
                 * 是因為客戶端取消了下載,而服務器端繼續向瀏覽器寫入數據時, 拋出這個異常,這個是正常的。
                 * 尤其是對於迅雷這種吸血的客戶端軟件, 明明已經有一個線程在讀取 bytes=1275856879-1275877358,
                 * 如果短時間內沒有讀取完畢,迅雷會再啟第二個、第三個。。。線程來讀取相同的字節段, 直到有一個線程讀取完畢,迅雷會 KILL
                 * 掉其他正在下載同一字節段的線程, 強行中止字節讀出,造成服務器拋 ClientAbortException。
                 * 所以,我們忽略這種異常
                 */
                logger.debug("提醒:向客戶端傳輸時出現IO異常,但此異常是允許的,有可能客戶端取消了下載,導致此異常,不用關心!");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * 修正路徑,將 \\ 或 / 等替換為 File.separator
     * @param path 待修正的路徑
     * @return 修正后的路徑
     */
    public static String path(String path){
        String p = StringUtils.replace(path, "\\", "/");
        p = StringUtils.join(StringUtils.split(p, "/"), "/");
        if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")){
            p += "/";
        }
        if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")){
            p = p + "/";
        }
        if (path != null && path.startsWith("/")){
            p = "/" + p; // linux下路徑
        }
        return p;
    }
    
    /**
     * 獲目錄下的文件列表
     * @param dir 搜索目錄
     * @param searchDirs 是否是搜索目錄
     * @return 文件列表
     */
    public static List<String> findChildrenList(File dir, boolean searchDirs) {
        List<String> files = Lists.newArrayList();
        for (String subFiles : dir.list()) {
            File file = new File(dir + "/" + subFiles);
            if (((searchDirs) && (file.isDirectory())) || ((!searchDirs) && (!file.isDirectory()))) {
                files.add(file.getName());
            }
        }
        return files;
    }

    /**
     * 獲取文件擴展名(返回小寫)
     * @param fileName 文件名
     * @return 例如:test.jpg  返回:  jpg
     */
    public static String getFileExtension(String fileName) {
        if ((fileName == null) || (fileName.lastIndexOf(".") == -1) || (fileName.lastIndexOf(".") == fileName.length() - 1)) {
            return null;
        }
        return StringUtils.lowerCase(fileName.substring(fileName.lastIndexOf(".") + 1));
    }

    /**
     * 獲取文件名,不包含擴展名
     * @param fileName 文件名
     * @return 例如:d:\files\test.jpg  返回:d:\files\test
     */
    public static String getFileNameWithoutExtension(String fileName) {
        if ((fileName == null) || (fileName.lastIndexOf(".") == -1)) {
            return null;
        }
        return fileName.substring(0, fileName.lastIndexOf("."));
    }
    
    /**
     * 獲取文件大小
     * @param file
     * @return
     * @author guogf
     */
    public static String getFileSize(MultipartFile file) {
        DecimalFormat df = new DecimalFormat("0.00");
        String fileSizeString = "";
        if (file.getSize() < 1024) {
            fileSizeString = df.format((double) file.getSize()) + "B";
        } else if (file.getSize() < 1048576) {
            fileSizeString = df.format((double) file.getSize() / 1024) + "K";
        } else if (file.getSize() < 1073741824) {
            fileSizeString = df.format((double) file.getSize() / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) file.getSize() / 1073741824) + "G";
        }
        return fileSizeString;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM