1. 程式人生 > >java 單個上傳檔案, 批量上傳檔案,單個下載,批量打成zip壓縮包下載檔案(如果不能接受httpsevletrequest請求的檔案可以使用MultipartFile[] files)

java 單個上傳檔案, 批量上傳檔案,單個下載,批量打成zip壓縮包下載檔案(如果不能接受httpsevletrequest請求的檔案可以使用MultipartFile[] files)

package net.wkang.intelligent_audit.hospitalization.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Configuration
public class FileUploadDownload {
    /**
     * 單檔案上傳
     * @param file
     * @return
     */
    public Map<String, Object> upload(MultipartFile file){
        Map<String, Object> map = new HashMap<String,Object>();
        if(file==null) {
            map.put("message", "沒有發現檔案!");
            return map;
        } 
        if (file.isEmpty()) {
            map.put("message", "檔案不能為空!");
            return map;
        }
         // 獲取檔名
        String fileName=file.getOriginalFilename();
      
            System.out.println("上傳的檔名為:" + fileName);
            // 獲取檔案的字尾名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上傳的字尾名為:" + suffixName);
            // 檔案上傳後的路徑
            String filePath = "upload/";
            // 解決中文問題,liunx下中文路徑,圖片顯示問題
            // fileName = UUID.randomUUID() + suffixName;
            String absolutePath = new File(filePath + fileName).getAbsolutePath();//獲取絕對路徑
            map.put("path", absolutePath);
            System.out.println(absolutePath);
            File dest = new File(absolutePath);
            // 檢測是否存在目錄
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                map.put("message", "上傳成功");
                return map;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            map.put("message", "上傳失敗");
            return map;
    }
    
    /**
     * 批量上傳
     * @param orderId 
     * */
    public Map<String, Object> handleFileUpload(HttpServletRequest request, String orderId) {
        Map<String, Object> map = new HashMap<String,Object>();
        List<String> listFileName = new ArrayList<String>();
        List<String> listFilePath = new ArrayList<String>();
        System.out.println(request.getParameter("file"));
        
             List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                        .getFiles("file");
             String realPath = "upload/"+orderId+"/";
             File dest = new File(realPath + " ");
                // 檢測是否存在目錄
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                MultipartFile file = null;
                BufferedOutputStream stream = null;
                for (int i = 0; i < files.size(); ++i) {
                    file = files.get(i);
                    if (!file.isEmpty()) {
                        try {
                            byte[] bytes = file.getBytes();
                            stream = new BufferedOutputStream(new FileOutputStream(
                                    new File(realPath,file.getOriginalFilename())));
                            listFileName.add(file.getOriginalFilename());
                            listFilePath.add(realPath+file.getOriginalFilename());
                            stream.write(bytes);
                            stream.close();
                        } catch (Exception e) {
                            stream = null;
                            map.put("message", "上傳失敗");
                            return map;//上傳失敗
                        }
                    } else {
                        map.put("message", "第"+i+"個檔案上傳失敗");
                        return map;
                    }
                }
                map.put("listFileName", listFileName);
                map.put("listFilePath", listFilePath);
                map.put("message", "上傳成功");
                return map;
         }         
    /**
     * 單個下載
     * @return
     */
    public  Map<String, Object> download(HttpServletResponse response,String fileName,String orderId){
        Map<String, Object> map = new HashMap<String,Object>();
            if (fileName != null) {
                //檔案下載路徑,應與檔案上傳路徑一致
                String realPath = "upload/"+orderId+"/";
                File file = new File(realPath, fileName);
                if (file.exists()) {
                     try {
                        fileName = new String(fileName.getBytes(),"ISO8859-1");//防止中文名稱亂碼
                    } catch (UnsupportedEncodingException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } 
                    response.setContentType("application/force-download");// 設定強制下載不開啟
                    response.addHeader("Content-Disposition",
                            "attachment;fileName=" +  fileName);// 設定檔名
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    OutputStream os = null;
                    try {
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                        map.put("message", "下載成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        map.put("message", "下載失敗");
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if(os !=null) {
                            try {
                                os.flush();
                                os.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            
                        }
                    }
                }
            }
            return map;
    }
    /**
     * 下載多檔案zip壓縮檔案
     * @param response
     */
    public void FileDownload(HttpServletResponse response) {
//        String realPath = "upload/";
            //需要壓縮的檔案--包括檔案地址和檔名
            String []path ={"D:\\git\\intelligent_audit_system\\intelligent-audit-biz-hospitalization\\upload\\配置.txt",
            "D:\\git\\intelligent_audit_system\\intelligent-audit-biz-hospitalization\\upload\\新建文字文件.txt"};
            // 要生成的壓縮檔案地址和檔名稱
            String desPath = "D:\\DownLoad.zip";
            File zipFile = new File(desPath);
            ZipOutputStream zipStream = null;
            FileInputStream zipSource = null;
            BufferedInputStream bufferStream = null;
            try {
                //構造最終壓縮包的輸出流
                zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
                for(int i =0;i<path.length;i++){
                    File file = new File(path[i]);
                    //將需要壓縮的檔案格式化為輸入流
                    zipSource = new FileInputStream(file);
                    //壓縮條目不是具體獨立的檔案,而是壓縮包檔案列表中的列表項,稱為條目,就像索引一樣
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    //定位該壓縮條目位置,開始寫入檔案到壓縮包中

                    zipStream.putNextEntry(zipEntry);

                    //輸入緩衝流
                    bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                    int read = 0;
                    //建立讀寫緩衝區
                    byte[] buf = new byte[1024 * 10];
                    while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
                    {
                        zipStream.write(buf, 0, read);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //關閉流
                try {
                    if(null != bufferStream) bufferStream.close();
                    if(null != zipStream) zipStream.close();
                    if(null != zipSource) zipSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    }