h5上傳圖片壓縮包服務端解壓并上傳圖片

CMS后臺有上傳多個圖片的需求,多個圖片上傳也一樣麻煩。就想做個上傳壓縮包服務端解壓上傳的東西。

頁面

使用h5的上傳api

      /*
             *
             * name: 上傳字段標示
             postUrl: 文件數據處理URL
             onClientAbort: 讀取操作終止時調用
             onClientError: 出錯時調用
             onClientLoad: 讀取操作成功時調用
             onClientLoadEnd: 無論是否成功,讀取完成時調用。通常在onload和onerror后調用
             onClientLoadStart: 讀取將要開始時調用
             onClientProgress: 數據在讀取過程中周期性調用
             onServerAbort: post操作結束時調用
             onServerError: 錯誤發生時調用
             onServerLoad: post操作成功時調用
             onServerLoadStart: post數據將要開始時調用
             onServerProgress: 數據正在被post的過程中周期性調用
             onServerReadyStateChange: 一個javascript功能對象無論任何時候readyState屬性變化時調用。callback由用戶界面現成調用。
             *
             *
             * */

            $("#uploadZip").html5Uploader({
                url: "rest/material/uploadZip",
                onSuccess: function (e, file, response) {
                    var res = JSON.parse(response);
                    if (res == "200") {
                        $.sticky("已經成功上傳并且存入原始素材庫!");
                        swal("SUCCESS!", "已經成功上傳并且存入原始素材庫!", "success");
                    } else {
                        $.sticky("壓縮格式錯誤或壓縮過程出現錯誤");
                        swal("OMG!", "壓縮包有錯誤請重新壓縮并重新上傳 = = ?。。?, "error");
                    }
                },
                onClientLoad: function () {
                    $.sticky("文件讀取成功! ! !");
                },
                onClientLoadEnd: function () {
                    $.sticky("文件上傳完成! ! !");
                },
                onClientLoadStart: function () {
                    $.sticky("文件將要開始讀取! ! !");
                },
                onClientProgress: function () {

                },
                onServerError: function () {
                    console.log(11111111 + "========")
                },
                onServerProgress: function () {
                    $.sticky("文件正在上傳! ! !");
                }
            });

用了一些美化過的彈窗控件

SweetAlert

引入js就行了。

后臺模板之前常用ACE的。
扣下來改吧改吧。

服務端

服務端用的Java寫的。


    @Transactional
    @RequestMapping(value = "uploadZip", method = RequestMethod.POST)
    public Map<String, Object> uploadZip(HttpServletRequest request) throws Exception {

        Map<String, Object> result = new HashMap<>();
        User user = GrantedFilter.threadLocal.get();
        final Integer userId = user.getId();

        Uploader uploader = new Uploader(request);
        // 解壓
        final File[] fileList = uploader.uploadMaterialZip();
        // 有時候壓縮會出問題  Mac 和 Windows 
        if (fileList.length < 1 || fileList.length>1?fileList[1].isDirectory():fileList[0].isDirectory()) {
            File f = null;
            try {
                f = new File(fileList[0].getParent());
                deleteFile(f);
            } catch (Exception e) {

            }
            result.put("code", "400");
            return result;
        } else {
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    String temp = fileList[0].getParent();
                    for (File file : fileList) {
                        if (file.getName().endsWith(".gif")||file.getName().endsWith(".GIF")) {
                            UFileRequest uFileRequest = new UFileRequest();
                            String gifKey = RandomStringUtils.randomAlphanumeric(32) + ".gif";
                            uFileRequest.setBucketName(SysConfigDao.getValue(SysConfig.otherConfig, "ufile_bucket"));
                            uFileRequest.setFilePath(file.getPath());
                            uFileRequest.setKey(gifKey);
                            uFileAPI.putFile(uFileRequest);
                            String url = uFileAPI.getDownloadUrl(uFileRequest, 0, false);
                            MaterialRaw materialRaw = new MaterialRaw();
                            materialRaw.setTag("3");
                            materialRaw.setGifurl(url);
                            materialRaw.setCreateAt(new Date());
                            materialRaw.setStatus("t");
                            materialRaw.setChannl("r");
                            try {
                                materialRaw.setMd5(MD5Util.getMd5ByFile(file));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            materialRaw.setSize((int) file.length());
                            materialRaw.setCreateBy(userId);
                            try {
                                materialRaw.setTitle(file.getName().substring(0, file.getName().lastIndexOf(".gif")));
                            } catch (Exception e) {
                                materialRaw.setTitle(file.getName().substring(0, file.getName().lastIndexOf(".GIF")));
                            }
                            materialRawDao.save(materialRaw);
                        }
                        file.delete();
                    }
                    File f = new File(temp);
                    deleteFile(f);
                }
            });
        }
        result.put("code", "200");
        return result;
    }


解壓的Util類

    public File[] uploadMaterialZip() throws Exception {
        originalName = request.getHeader("X-File-Name");
        type = FileUtil.getFileExt(originalName);
        if (!".zip".equals(type.toLowerCase())) {
            throw new BadRequestException("格式錯誤!");
        }
        if (request.getContentLength() / 1024000 > 100) {
            throw new BadRequestException("文件太大!");
        }
        fileName = Util.RunTimeSequence() + type;
        path = DateUtil.zipDateFormat(new Date()) + File.separator + fileName;
        File file = new File(savePath + File.separator + path);
        file.getParentFile().mkdirs();
        try (InputStream is = request.getInputStream();
             FileOutputStream fos = new FileOutputStream(file)) {
            IOUtils.copy(is, fos);
            size = file.length();
        }
        String str = savePath + File.separator + System.currentTimeMillis();
        File dir = new File(str);
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdirs();
        }
        String temp = savePath + File.separator + DateUtil.zipDateFormat(new Date()) + File.separator;
        // 加壓的工具類
        DeCompressUtil.deCompress(savePath + File.separator + path, str, temp);
        File gifFile = new File(str);
        File[] fileList = gifFile.listFiles();
        if (fileList.length<1){
            gifFile.delete();
        }
        return fileList;
    }

解壓

package com.an.core.utils.zip;

import com.an.core.exception.BadRequestException;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;

import java.io.File;
import java.io.FileOutputStream;

public class DeCompressUtil {
    /**
     * 解壓zip格式壓縮包
     * 對應的是ant.jar
     */
    private static void unzip(String sourceZip, String destDir, String temp) throws Exception {
        try {
            Project p = new Project();
            Expand e = new Expand();
            e.setProject(p);
            e.setSrc(new File(sourceZip));
            e.setOverwrite(false);
            e.setDest(new File(destDir));
           /*
           ant下的zip工具默認壓縮編碼為UTF-8編碼,
           而winRAR軟件壓縮是用的windows默認的GBK或者GB2312編碼
           所以解壓縮時要制定編碼格式
           */

            try {
                e.setEncoding("GBK");
                e.execute();
            } catch (Exception e1) {
                e.setEncoding("UTF-8");
                e.execute();
            }
            File zipFile = new File(sourceZip);
            File zipPath = new File(temp);
            zipFile.delete();
            zipPath.delete();

        } catch (Exception e) {
            throw new BadRequestException(e);
        }
    }

    /**
     * 解壓rar格式壓縮包。
     * 對應的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又會用到commons-logging-1.1.1.jar
     */
    private static void unrar(String sourceRar, String destDir, String temp) throws Exception {
        Archive a = null;
        FileOutputStream fos = null;
        try {
            a = new Archive(new File(sourceRar));
            FileHeader fh = a.nextFileHeader();
            while (fh != null) {
                if (!fh.isDirectory()) {
                    //1 根據不同的操作系統拿到相應的 destDirName 和 destFileName
                    String compressFileName = fh.getFileNameString().trim();
                    String destFileName = "";
                    String destDirName = "";
                    //非windows系統
                    if (File.separator.equals("/")) {
                        destFileName = destDir + compressFileName.replaceAll("\\\\", "/");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
                        //windows系統
                    } else {
                        destFileName = destDir + compressFileName.replaceAll("/", "\\\\");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
                    }
                    //2創建文件夾
                    File dir = new File(destDirName);
                    if (!dir.exists() || !dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    //3解壓縮文件
                    fos = new FileOutputStream(new File(destFileName));
                    a.extractFile(fh, fos);
                    fos.close();
                    fos = null;
                }
                fh = a.nextFileHeader();
            }
            a.close();
            a = null;
        } catch (Exception e) {
            throw e;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (a != null) {
                try {
                    a.close();
                    a = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 解壓縮
     */
    public static void deCompress(String sourceFile, String destDir, String temp) throws Exception {
        //保證文件夾路徑最后是"/"或者"\"
        char lastChar = destDir.charAt(destDir.length() - 1);
        if (lastChar != '/' && lastChar != '\\') {
            destDir += File.separator;
        }
        //根據類型,進行相應的解壓縮
        String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
        if (!".zip".equals(type.toLowerCase())) {
            DeCompressUtil.unzip(sourceFile, destDir, temp);
        } else if (type.equals("rar")) {
            DeCompressUtil.unrar(sourceFile, destDir, temp);
        } else {

        }
    }
} 

刪除文件夾下面的所有內容

    /**
     * 刪除文件夾所有的文件和文件夾
     *
     * @param file
     */
    public static void deleteFile(File file){
        if(file.isFile()){
            file.delete();
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
                RecursionDeleteFile(f);
            }
            file.delete();
        }
    }

之前有找過一個Demo

下載鏈接

希望對你有幫助 ??????。

歡迎光臨我的個人博客

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,048評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,414評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,169評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,722評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,465評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,823評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,813評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,000評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,554評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,295評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,513評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,722評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,125評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,430評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,237評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,482評論 2 379

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,728評論 25 708
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,825評論 18 139
  • ORID總結今天滿月了,經過一個月的訓練,在結構上基本掌握了,接下來的一段時間,我將復盤自己的培訓技巧。 為了更直...
    學前班77閱讀 902評論 7 3
  • 0. 前言 在開發過程中會對數組進行操作,而方法很多,我在這里進行一些總結。 1. 簡介 數組可以存儲多個不同類型...
    舊丶時候閱讀 526評論 0 6
  • 今天不適合 詠月 今天不適宜 思念 今天不應該 孤單 今天不知道 用什麼樣的文字 說著自己 祝福的話語 是 挑動 ...
    蔡振源閱讀 383評論 0 1