1. 程式人生 > >Spring MVC 中檔案上傳/刪除 刪除空資料夾方法 + 下載方法

Spring MVC 中檔案上傳/刪除 刪除空資料夾方法 + 下載方法

package com.pqs.common.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class Upload {
 private static Logger log = LoggerFactory.getLogger(Upload.class);
 private static final int BUFFER_SIZE = 16 * 1024 ;
 
    public void upload(File f,String fileName){
  try {
   //建立讀取流
   FileInputStream fin = new FileInputStream(f);
   String files = Thread.currentThread().getContextClassLoader().getResource("/").getPath()+"upload/";
   
   //建立輸入流
   File fe = new File(files+fileName);
   
   FileOutputStream fout = new FileOutputStream(fe);
   
   //一邊讀取,一邊寫入
   byte data[] = new byte[1024];
   
   int count = 0;
   
   while((count=fin.read(data))!=-1){
    
    fout.write(data, 0, count);
   }
   
   //關閉流
   fin.close();
   fout.close();
   
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  
 }
 /**
  * 圖片上傳方法
  * @param f 檔案
  * @param fName 圖片名稱
  * @param paperFileName 資料夾名稱
  * @return
  */
    public final static String uploadImg(HttpServletRequest request, MultipartFile f, String fName, String paperFileName){
  if(null != f && null!=fName) {
   String imageFileName = new Date().getTime() + getExtention(fName);// 生成處理後在圖片名稱
     String filedir = request.getSession().getServletContext().getRealPath("/") + "uploads/"
       +"/"+paperFileName;
   File dir = new File(filedir);
   if (!dir.exists())   //如果目錄不存在就建立目錄
    dir.mkdirs();
   File imageFile = new File(filedir + "/" + imageFileName);
   try {
    copyFile(f, imageFile);
   } catch (Exception e) {
    e.printStackTrace();
   }
   return "uploads/"+paperFileName+"/"+imageFileName; //新生成的圖片路徑名稱
  }
 
 return null;
  }
  //擷取圖片名字
  private static String getExtention(String fileName) {
      int pos = fileName.lastIndexOf( "." );
      return fileName.substring(pos);
  }
 //存入圖片
  private static void copyFile(MultipartFile imgFile, File dst) throws IOException  {
     imgFile.transferTo(dst); //儲存上傳的檔案 
  }
 
  /**
   * 儲存檔案
   * @param f 檔案
   * @param fName 檔名稱
   * @param paperFileName 資料夾名稱
   * @return
   */
  public final static String uploadFile(HttpServletRequest request, MultipartFile f, String fName, String paperFileName){
   if(f.getSize()!=0 &&!("").equals(fName) && null!=f && null!=fName){
    String filedir = request.getSession().getServletContext().getRealPath("/") + "uploads/"+paperFileName;
    File dir = new File(filedir);
    if (!dir.exists()) //如果目錄不存在就建立目錄
    dir.mkdirs();
    File accessoryFile = new File(filedir + "/" + fName); //NEW一個檔案物件
    try {
    copyFile(f, accessoryFile); //拷貝上傳的檔案物件
   } catch (Exception e) {
    e.printStackTrace();
   }
    return "uploads/"+paperFileName+"/"+fName; //新生成的圖片路徑名稱
   }
  return null; 
  }
  /******************************************************************************************************************/
  /**
   * 刪除檔案
   * @param fName 檔名稱
   * @param paperFileName 資料夾名稱
   * @return
   */
  public final static boolean deleteFileOrDirectory(HttpServletRequest request, String fName, String paperFileName){
   //檔案路徑
   String filedir = request.getSession().getServletContext().getRealPath("/") + "uploads/"+paperFileName+"/"+fName;
   //資料夾
   String directorydir = request.getSession().getServletContext().getRealPath("/") + "uploads/"+paperFileName;
   //儲存檔案 資料夾路徑
   String rootPath = request.getSession().getServletContext().getRealPath("/") + "uploads";
   File file = new File(filedir);
   if (!file.exists()) {
    //"刪除檔案失敗:"+fName+"檔案不存在";
  return false;
 }else{
  //刪除所有空資料夾
  List<File> list = getAllNullDirectorys(new File(rootPath));
   removeNullFile(list, rootPath);
   if(file.isFile()){   
             return deleteFile(filedir);  //刪除單個檔案    
         }else{   
             return deleteDirectory(directorydir);  //刪除目錄(資料夾)以及目錄下的檔案  
         } 
 }
  }
 
  /**  
   * 刪除單個檔案  
   * @param   fileName    被刪除檔案的檔名  
   * @return 單個檔案刪除成功返回true,否則返回false  
   */  
  public static boolean deleteFile(String fileName){
   File file = new File(fileName);
   if (file.isFile() && file.exists()) {
  file.delete();//"刪除單個檔案"+name+"成功!"
  return true;
   }//"刪除單個檔案"+name+"失敗!"
   return false;
  }
 
  /**  
   * 刪除目錄(資料夾)以及目錄下的檔案  
   * @param   dir 被刪除目錄的檔案路徑  
   * @return  目錄刪除成功返回true,否則返回false  
   */
  public static boolean  deleteDirectory(String directorydir){   
      //如果dir不以檔案分隔符結尾,自動新增檔案分隔符 
      if(!directorydir.endsWith(File.separator)){   
       directorydir = directorydir+File.separator;   
      }   
      File dirFile = new File(directorydir);   
      //如果dir對應的檔案不存在,或者不是一個目錄,則退出   
      if(!dirFile.exists() || !dirFile.isDirectory()){  
       //"刪除目錄失敗"+name+"目錄不存在!"
          return false;   
      }   
      boolean flag = true;   
      //刪除資料夾下的所有檔案(包括子目錄)   
      File[] files = dirFile.listFiles();   
      for(int i=0;i<files.length;i++){   
          //刪除子檔案   
          if(files[i].isFile()){   
              flag = deleteFile(files[i].getAbsolutePath());   
              if(!flag){   
                  break;   
              }   
          }   
          //刪除子目錄   
          else{   
              flag = deleteDirectory(files[i].getAbsolutePath());   
              if(!flag){   
                  break;   
              }   
          }   
      }   
          
      if(!flag){   
          //System.out.println("刪除目錄失敗");   
          return false;   
      }   
          
      //刪除當前目錄   
      if(dirFile.delete()){   
          //System.out.println("刪除目錄"+directorydir+"成功!");   
          return true;   
      }else{
          //System.out.println("刪除目錄"+directorydir+"失敗!");   
          return false;   
      }
  }
 
  //刪除資料夾 folderPath 資料夾完整絕對路徑
  public static void delFolder(String folderPath) {
       try {
          delAllFile(folderPath); //刪除完裡面所有內容
          String filePath = folderPath;
          filePath = filePath.toString();
          java.io.File myFilePath = new java.io.File(filePath);
          myFilePath.delete(); //刪除空資料夾
       } catch (Exception e) {
         e.printStackTrace();
       }
    }
 
  //刪除指定資料夾下所有檔案 path 資料夾完整絕對路徑
     public static boolean delAllFile(String path) {
         boolean flag = false;
         File file = new File(path);
         if (!file.exists()) {
           return flag;
         }
         if (!file.isDirectory()) {//判斷該路徑是否是一個目錄
           return flag;
         }
         String[] tempList = file.list();
         File temp = null;
         for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
               temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
               temp.delete();
            }
            if (temp.isDirectory()) {
               delAllFile(path + "/" + tempList[i]);//先刪除資料夾裡面的檔案
               delFolder(path + "/" + tempList[i]);//再刪除空資料夾
               flag = true;
            }
         }
         return flag;
       }
   
    /*public static void main(String[] args) {
        //String fileName = "g:/temp/xwz.txt";   
        //DeleteFileUtil.deleteFile(fileName);   
        String fileDir = "D:\\apache-tomcat-6.0.18\\webapps\\cyfy\\upload\\disk\\1245117448156\\JavaScript486.rar";   
        //DeleteFileUtil.deleteDirectory(fileDir);   
       
        DeleteFileUtil.delete(fileDir);  
        DeleteFileUtil t = new DeleteFileUtil();
        delFolder("c:/bb");
        System.out.println("deleted");
       
    } */
    /******************************************************************************************************************/
    //刪除指定路徑下所有空資料夾
     public static void main(String[] args) {
   //要刪除的目錄 請勿以\\結尾,及最後一層目錄後的分隔符不要
   String rootPath = "D:\\UsersMyEclipse10Space\\JYCRM\\WebRoot\\uploads";
   List<File> list = getAllNullDirectorys(new File(rootPath));
   //System.out.println("---------------" + list.size());
   /*for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i).getPath());
   }*/
   removeNullFile(list, rootPath);
  }
    
  /**
   * 遞迴列出某資料夾下的最深層的空資料夾絕對路徑,儲存至list
   *
   * @param root
   * @return
   */
  public static List<File> getAllNullDirectorys(File root) {
   List<File> list = new ArrayList<File>();
   File[] dirs = root.listFiles();
   if (dirs != null) {
    for (int i = 0; i < dirs.length; i++) {
     if (dirs[i].isDirectory() && dirs[i].listFiles().length == 0) {
      //System.out.println("name:" + dirs[i].getPath());
      list.add(dirs[i]);
     }
     if(dirs[i].isFile()){
      //System.out.println("檔案:"+dirs[i].getPath());
    }
    list.addAll(getAllNullDirectorys(dirs[i]));
   }
  }
  return list;
 }

 /**
  * 由最深一層的空檔案,向上(父資料夾)遞迴,刪除空資料夾
  * @param list
  * @param rootPath
  */
 public static void removeNullFile(List<File> list, String rootPath) {
  if (list==null||list.size()==0) {
   return;
  }
  List<File> plist = new ArrayList<File>();
  for (int i = 0; i < list.size(); i++) {
   File temp = list.get(i);
   if (temp.isDirectory()  && temp.listFiles().length <= 0  ) {
    temp.delete();
    //System.out.println("parent:" + temp.getParentFile().getPath());
    File pFile = temp.getParentFile();
    if (pFile.getPath().equals(rootPath)) {
     continue;
    }
    if (!plist.contains(pFile)) {//父目錄去重新增
     plist.add(pFile);
    }
   }
  }
  removeNullFile(plist, rootPath);
 }

/**
 * 下載
 * @author geloin
 * @date 2012-5-5 下午12:25:39
 * @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("/")+ "uploads/"; 
    String downLoadPath = ctxPath + storeName; 
  
    long fileLength = new File(downLoadPath).length(); 
  
    response.setContentType(contentType); 
    response.setHeader("Content-disposition", "attachment; filename=" 
            + new String(realName.getBytes("gb2312"), "ISO-8859-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(); 
 }


}