阿里OSS Java-SDK带进度条上传,配合前端element-ui upload组件使用示例

版权声明:本文为博主原创文章,欢迎转载,转载请注明出处 https://blog.csdn.net/m0_37893932/article/details/79032343

阿里OSS Java-SDK 文件上传-上传进度条文档链接

OSS上传工具类,其中有注释的几步是官网例子所没有的步骤.

public class OssUploadUtil {

/**
     * 带进度的上传
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static String uploadPicWithProgress(HttpServletRequest request) throws Exception {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "<yourAccessKeyId>";
        String accessKeySecret = "<yourAccessKeySecret>";
        String bucketName = "<yourBucketName>";
        PropertiesUtil util = PropertiesUtil.getPropertiesUtil();
        util.loadProperties("resource/oss.properties");
        filePath = util.getValueFromProperties("url.oss.secretFilePath");  //文件路径
        bucketName = util.getValueFromProperties("url.oss.secretBucketName"); //BucketName
        String ossPath = util.getValueFromProperties("video.url");
        DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
        request.setCharacterEncoding("UTF-8");
        Map<String, MultipartFile> files = req.getFileMap();
        int i = 0;
        StringBuffer totalPath = new StringBuffer();
        for (String key : files.keySet()) {
            String suffix = "";
            OSSClient oSSClient = new OSSClient(PROTOCOL + endpoint, accessKeyId, accessKeySecret);
            MultipartFile file = files.get(key);

            /* MultipartFile转File  */
            File f = null;
            try {
                f = File.createTempFile("tmp", null);
                file.transferTo(f);
                f.deleteOnExit();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (file.getOriginalFilename().contains(".")) {
                suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            String fileName = System.currentTimeMillis() + i + suffix;
            i++;
            try {
         /*
         这里用带进度条的OSS上传 
         将session传入PutObjectProgressListener的构造中!官网例子是没有这个操作的
         注意new PutObjectRequest()的第三个参数是File而不是官网介绍的FileInputStream,否则获取不到进度.
        */
                PutObjectResult putObjectResult = oSSClient.putObject(new PutObjectRequest(bucketName, ossPath + fileName, f).
                        <PutObjectRequest>withProgressListener(new PutObjectProgressListener(request.getSession())));
            } catch (OSSException oe) {
                logger.error("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.Error Message: " + oe.getErrorCode()
                        + "Error Code:" + oe.getErrorCode() + "Request ID:" + oe.getRequestId() + "Host ID:" + oe.getHostId(), oe);
                throw new OSSException(oe.getErrorMessage(), oe);
            } catch (ClientException ce) {
                logger.error("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.Error Message:" + ce.getMessage(), ce);
                throw new ClientException(ce);
            } finally {
                oSSClient.shutdown();
            }
            totalPath.append(filePath + SEPARATOR + ossPath + fileName + ",");
        }
        totalPath.deleteCharAt(totalPath.length() - 1);
        return totalPath.toString();
    }

    public static class PutObjectProgressListener implements ProgressListener {
        private HttpSession session;
        private long bytesWritten = 0;
        private long totalBytes = -1;
        private boolean succeed = false;
        private int percent = 0;

        //构造方法中加入session
        public PutObjectProgressListener() {
        }
        public PutObjectProgressListener(HttpSession mSession) {
            this.session = mSession;
            session.setAttribute("upload_percent", percent);
        }

        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
                case TRANSFER_STARTED_EVENT:
                    logger.info("Start to upload......");
                    break;
                case REQUEST_CONTENT_LENGTH_EVENT:
                    this.totalBytes = bytes;
                    logger.info(this.totalBytes + " bytes in total will be uploaded to OSS");
                    break;
                case REQUEST_BYTE_TRANSFER_EVENT:
                    this.bytesWritten += bytes;
                    if (this.totalBytes != -1) {
                        percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                        //将进度percent放入session中
                        session.setAttribute("upload_percent", percent);
                        logger.info(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                    } else {
                        logger.info(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
                    }
                    break;
                case TRANSFER_COMPLETED_EVENT:
                    this.succeed = true;
                    logger.info("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
                    break;
                case TRANSFER_FAILED_EVENT:
                    logger.info("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                    break;
                default:
                    break;
            }
        }

        public boolean isSucceed() {
            return succeed;
        }
    }
}

控制层的方法

/**
     * 上传文件
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping ("item/upload")
    @ResponseBody
    public String uploadSection(HttpServletRequest request) throws Exception {
        return UploadUtil.uploadPicWithProgress(request);
    }

    /**
     * 获取实时长传进度
     * @param request
     * @return
     */
    @RequestMapping ("item/percent")
    @ResponseBody
    public int getUploadPercent(HttpServletRequest request){
        HttpSession session = request.getSession();
        int percent = session.getAttribute("upload_percent") == null ? 0: (int) session.getAttribute("upload_percent");
        return percent;
    }

    /**
     * 重置上传进度
     * @param request
     * @return
     */
    @RequestMapping ("/percent/reset")
    public void resetPercent(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("upload_percent",0);
    }

前端进度条相关代码

采用element-ui的进度条做的,它是基于VUE的,uploadPercent就是上传进度

<el-progress v-show="showProgress" :text-inside="true" :stroke-width="18" :percentage="uploadPercent"></el-progress>

var vm = new Vue({
    el: '#app',
    data: {
        uploadPercent: 0,
        i: 0
    },
    methods: {
        handleProgress: function (event, file, fileList) { //课程上传中的钩子
            if(vm.i == 0){ //控制上传中状态只执行一次上传
                    vm.showStatus();
                    vm.showProgress = true;
                    vm.i = 1;
                }
            },
            showStatus: function () { //定时查询上传进度 0.1秒查一次
                var intervalId = setInterval(function () {
                    $.get("/section/item/percent", {}, function (data) {
                        console.log(data);
                        var percent = data;
                        if (percent >= 100) {
                            clearInterval(intervalId);
                            percent = 100;//不能大于100
                        }
                        vm.uploadPercent = percent;
                    }, "json");
                }, 100);
            },
            resetPercent: function () { //重置上传进度
                $.post("/section/percent/reset");
            },
    }
})

猜你喜欢

转载自blog.csdn.net/m0_37893932/article/details/79032343