美文网首页程序员
h5上传图片压缩包服务端解压并上传图片

h5上传图片压缩包服务端解压并上传图片

作者: YoRuo_ | 来源:发表于2016-12-13 16:51 被阅读658次

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

下载链接

希望对你有帮助 😂😂😂。

欢迎光临我的个人博客

相关文章

  • h5上传图片压缩包服务端解压并上传图片

    CMS后台有上传多个图片的需求,多个图片上传也一样麻烦。就想做个上传压缩包服务端解压上传的东西。 页面 使用h5的...

  • 上传图片预览并截取

    场景:上传图片,裁剪相应格式,并保存到服务端(上传图片当头像)实现原理:1.客户端上传图片文件2.将图片文件转换成...

  • Webview图片上传方法

    H5交互-图片上传 图片上传 H5使用file标签进行文件上传,我们可以重写webview的webchromeCl...

  • RXJava应用系列-场景4

    四、上传反馈信息 场景描述: 首先上传用户图片,图片上传完成后把服务端返回的图片地址和反馈内容上传到服务器。 问题...

  • Laravel 中 bootstrap fileinput 图

    1、 图片上传并预览 效果展示: 2 图片上传成功之后的预览 图片上传之后编辑预览效果展示: 3 图片预...

  • 图片压缩上传

    参考1-HTML5实现图片压缩上传功能参考2-移动前端—图片压缩上传实践参考3-移动端H5图片压缩上传 大体步骤 ...

  • 【vue】vue-quill-editor富文本编辑器实现图片上

    封装vue-quill-editor实现富文本点击图标、选择文件、上传图片到服务端、上传成功返回图片地址、显示图片...

  • 基于html5+node.js 图片上传、预览实现

    1、检测浏览器是否支持 2、图片选取 3、图片预览 4、图片上传 图片上传分为前端和服务端 前端实现原理:XMLH...

  • 解决小程序webview中无法上传图片问题

    最近被支付宝小程序内嵌H5无法上传图片折磨到没脾气,H5本身上传图片没问题,但是嵌套在小程序中就无法上传。 在调试...

  • 小程序上传图片到七牛

    小程序上传图片到七牛云存储,服务端使用nodejs的thinkjs框架 服务端 小程序端 上传图片 效果如下: 本...

网友评论

    本文标题:h5上传图片压缩包服务端解压并上传图片

    本文链接:https://www.haomeiwen.com/subject/vbrbmttx.html