欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FTP、共享和本地三种情况下实现图片压缩后上传下载

程序员文章站 2024-03-13 23:34:58
...

       在网站的开发中,经常会使用到上传和下载图片的功能,可是有时候由于图片过大,或者所需下载的图片过多,为减少下载时间,提高下载速度,很多人都会想到通过压缩的方式进行上传或下载图片,最近刚好有一个项目使用了此功能,需要在FTP、共享和本地三种情况下实现图片压缩后上传下载,特在此对需要在代码进行分享记录,话不多说,直接上核心干货。

1、网页上下载图片压缩包

核心:

1)根据指定图片或图片路径获取到图片数据流

2)把图片流下载到临时文件中,并对其进行压缩

3)完成后删除临时文件,返回压缩包

4)删除压缩包

所需jar:

commons-compress-1.6.jar

核心处理代码如下:

public void zipImg(ZipArchiveOutputStream zaos,String pathtemp,byte[] data,String name) throws Exception{
        if(data != null){ 
            String nameTemp = name+"_"+new Date().getTime();
            File imageFileTemp = new File(pathtemp+File.separator+nameTemp+".jpg"); 
            //创建输出流 
            FileOutputStream outStream = new FileOutputStream(imageFileTemp); 
            //写入数据 
            outStream.write(data); 
            //关闭输出流 
            outStream.close(); 
            
            //获取创建好的图片文件 
            File imageFile = new File(pathtemp+"/"+nameTemp+".jpg"); 
            ZipArchiveEntry zipArchiveEntry  = new ZipArchiveEntry(imageFile,imageFile.getName());
            zaos.putArchiveEntry(zipArchiveEntry);
            zaos.write(data);
            zaos.closeArchiveEntry(); 
            // 压缩完删除txt文件 
            if (imageFile.exists()) { 
                imageFile.delete(); 
            } 
        }
    }
        //定义根路径 
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        String pathtemp = rootPath + "temp_download";
        File file = new File(pathtemp); //创建临时目录
        if(!file.exists()){ //判断文件是否存在,如果不存在,则创建此文件夹 
           file.mkdir(); 
        } 
        String zipFileName = title+"行李图片压缩包_"+creatDate + ".zip"; 
        File zipFile = new File(pathtemp + "/" + zipFileName); 
        ZipArchiveOutputStream zaos = null;
        try {
            zaos = new ZipArchiveOutputStream(zipFile);
            zaos.setUseZip64(Zip64Mode.AsNeeded);
            
            PropertiesConfig prop = new PropertiesConfig("general.properties");
            String mode = prop.getPropertieString("mode");
            if(mode.equals("Local")){//本地
                for(int i = 0 ;i<paths.size();i++){
                    try{
                        //调用工具类获取图片
                        byte[] data = ImageUtil.image2byte(paths.get(i));
                        zipImg(zaos,pathtemp,data,nameList.get(i));
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                }
                zaos.finish();
            }else if(mode.equals("CIFS")){//共享文件
                for(int i = 0 ;i<paths.size();i++){
                    try{
                        //调用工具类获取图片
                        byte[] data = SMBUtils.GetSMB().DownloadRemoteFile(paths.get(i));
                        zipImg(zaos,pathtemp,data,nameList.get(i));
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                }
                zaos.finish();
            }else if(mode.equals("FTP")){//FTP
                for(int i = 0 ;i<paths.size();i++){
                    try{
                        //调用工具类获取图片
                        byte[] data = FtpUtils.GetFTPClient().download(paths.get(i));
                        zipImg(zaos,pathtemp,data,nameList.get(i));
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                }
                zaos.finish();
            }
            file.delete();//删除临时目录
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(zaos != null) {
                    zaos.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        
     // 输出到客户端 
        OutputStream out = null; 
        out = response.getOutputStream(); 
        response.reset(); 
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFileName.getBytes("GB2312"), "ISO-8859-1")); 
        response.setContentType("application/octet-stream; charset=utf-8"); 
        response.setCharacterEncoding("UTF-8"); 
        out.write(FileUtils.readFileToByteArray(zipFile)); 
        out.flush(); 
        out.close(); 
        // 输出客户端结束后,删除压缩包 
        if (zipFile.exists()) { 
            zipFile.delete(); 
        } 

上传的流程与这差不多,就不在此共享了,另附赠一份完整的压缩解压工具类,用于压缩和解压指定目录下的所有文件

package com.ljb.ImageUtil;

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.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
 
public class ZipUtil {
    public static void main(String[] args) {
        String dir = "D:\\zip";
        String zippath = "D:\\zip\\test2.zip";
        ZipUtil.zip(dir, zippath);
 
////        String unzipdir = "D:\\test2";
//        String unzipdir = "D:\\zip\\img";
//        String unzipfile = "D:\\zip\\test2.zip";
//        ZipUtil.unzip(unzipfile, unzipdir);
//        System.out.println("success!");
    } 
    /**
     * zip压缩文件
     * @param dir
     * @param zippath
     */
    public static void zip(String dir ,String zippath){
        List<String> paths = getFiles(dir); 
        compressFilesZip(paths.toArray(new String[paths.size()]),zippath,dir);
    }
    /**
     * 递归取到当前目录所有文件
     * @param dir
     * @return
     */
    public static List<String> getFiles(String dir){
        List<String> lstFiles = null;       
        if(lstFiles == null){
            lstFiles = new ArrayList<String>();
        }
        File file = new File(dir);
        File [] files = file.listFiles(); 
        for(File f : files){
            if(f.isDirectory()){
                lstFiles.add(f.getAbsolutePath());
                lstFiles.addAll(getFiles(f.getAbsolutePath()));
            }else{ 
                String str =f.getAbsolutePath();
                lstFiles.add(str);
            }
        }
        return lstFiles;
    }
    
    /**
     * 文件名处理
     * @param dir
     * @param path
     * @return
     */
    public static String getFilePathName(String dir,String path){
        String p = path.replace(dir+File.separator, "");
        p = p.replace("\\", "/");
        return p;
    }
    /**
     * 把文件压缩成zip格式
     * @param files         需要压缩的文件
     * @param zipFilePath 压缩后的zip文件路径   ,如"D:/test/aa.zip";
     */
    public static void compressFilesZip(String[] files,String zipFilePath,String dir) {
        if(files == null || files.length <= 0) {
            return ;
        }
        ZipArchiveOutputStream zaos = null;
        try {
            File zipFile = new File(zipFilePath);
            zaos = new ZipArchiveOutputStream(zipFile);
            zaos.setUseZip64(Zip64Mode.AsNeeded);
            //将每个文件用ZipArchiveEntry封装
            //再用ZipArchiveOutputStream写到压缩文件中
            for(String strfile : files) {
                File file = new File(strfile);
                if(file != null) {
                    String name = getFilePathName(dir,strfile);
                    ZipArchiveEntry zipArchiveEntry  = new ZipArchiveEntry(file,name);
                    zaos.putArchiveEntry(zipArchiveEntry);
                    if(file.isDirectory()){
                        continue;
                    }
                    InputStream is = null;
                    try {
                        is = new BufferedInputStream(new FileInputStream(file));
                        byte[] buffer = new byte[1024 ]; 
                        int len = -1;
                        while((len = is.read(buffer)) != -1) {
                            //把缓冲区的字节写入到ZipArchiveEntry
                            zaos.write(buffer, 0, len);
                        }
                        zaos.closeArchiveEntry(); 
                    }catch(Exception e) {
                        throw new RuntimeException(e);
                    }finally {
                        if(is != null)
                            is.close();
                    }
                     
                }
            }
            zaos.finish();
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally {
                try {
                    if(zaos != null) {
                        zaos.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
         
    }
    
   
    /**
    * 把zip文件解压到指定的文件夹
    * @param zipFilePath zip文件路径, 如 "D:/test/aa.zip"
    * @param saveFileDir 解压后的文件存放路径, 如"D:/test/" ()
    */
    public static void unzip(String zipFilePath, String saveFileDir) {
        if(!saveFileDir.endsWith("\\") && !saveFileDir.endsWith("/") ){
            saveFileDir += File.separator;
        }
        File dir = new File(saveFileDir);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(zipFilePath);
        if (file.exists()) {
            InputStream is = null; 
            ZipArchiveInputStream zais = null;
            try {
                is = new FileInputStream(file);
                zais = new ZipArchiveInputStream(is);
                ArchiveEntry archiveEntry = null;
                while ((archiveEntry = zais.getNextEntry()) != null) { 
                    // 获取文件名
                    String entryFileName = archiveEntry.getName();
                    // 构造解压出来的文件存放路径
                    String entryFilePath = saveFileDir + entryFileName;
                    OutputStream os = null;
                    try {
                        // 把解压出来的文件写到指定路径
                        File entryFile = new File(entryFilePath);
                        if(entryFileName.endsWith("/")){
                            entryFile.mkdirs();
                        }else{
                            os = new BufferedOutputStream(new FileOutputStream(
                                    entryFile));                            
                            byte[] buffer = new byte[1024 ]; 
                            int len = -1; 
                            while((len = zais.read(buffer)) != -1) {
                                os.write(buffer, 0, len); 
                            }
                        }
                    } catch (IOException e) {
                        throw new IOException(e);
                    } finally {
                        if (os != null) {
                            os.flush();
                            os.close();
                        }
                    }
 
                } 
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (zais != null) {
                        zais.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}