oss上传文件进度条展示

Posted lh--yu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了oss上传文件进度条展示相关的知识,希望对你有一定的参考价值。

用户上传文件至oss的时候需要增加一个进度条展示,查看了官方文档及网上几篇博客后整理一下相关思路,在此记录一下自己的成长。

在此以上传视频为例,自定义监听监听文件上传进度,通过将字节数和总字节数之间比例写入session中返回给前端进行进度展示。

    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com"; 
    private static String accessKeyId = "<yourAccessKeyId>";
    private static String accessKeySecret = "<yourAccessKeySecret>";
    private static String bucketName = "<yourBucketName>";

/**
     * 上传私密文件至私有bucket
     * 上传至私有bucket的时候 返回key 每次通过key读取文件链接
     * 链接有效时间两小时
     * Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 2);
     * @Param uploadFile 上传文件
     * @Param picturePath key
     * @author LH_Yu
     */
    public static HashMap<String, Object> uploadOSSToll(MultipartFile uploadFile, String videoPath, HttpSession session) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        /**
         * 这里用带进度条的OSS上传
         * 将session传入PutObjectProgressListener的构造中!官网例子是没有这个操作的
         * 注意new PutObjectRequest()的第三个参数是File而不是官网介绍的FileInputStream,否则获取不到进度. 一定切记!!!
         * MultipartFile转File
         */
        File f = null;
        try {
            f = File.createTempFile("tmp", null);
            uploadFile.transferTo(f);
            f.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 上传  --> 不带进度条上传
//        ossClient.putObject(bucketNamePrivate, videoPath + uploadFile.getOriginalFilename(), new ByteArrayInputStream(uploadFile.getBytes()));
        // 上传 --> 带进度条上传
        ossClient.putObject(new PutObjectRequest(bucketNamePrivate, videoPath + uploadFile.getOriginalFilename(),f).withProgressListener(new PutObjectProgressListener(session)));
        // 关闭client
        ossClient.shutdown();
        //设置过期时间 -- 两小时
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 2);
        //取出文件上传路径
        String url = ossClient.generatePresignedUrl(bucketNamePrivate, videoPath + uploadFile.getOriginalFilename(), expiration).toString();
        map.put("key", videoPath + uploadFile.getOriginalFilename());
        map.put("url", url);
        return map;
    }
技术分享图片

自定义监听,监听文件上传进度

public static class PutObjectProgressListener implements ProgressListener {
    private long bytesWritten = 0;
    private long totalBytes = -1;
    private boolean succeed = false;
    private HttpSession session;
    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.debug("Start to upload......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                logger.debug(this.totalBytes + " bytes in total will be uploaded to OSS");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                    //将进度percent放入session中 官网demo中没有放入session这一步
                    session.setAttribute("upload_percent", percent);
                    logger.debug(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
                    logger.debug(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                logger.debug("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
                break;
            case TRANSFER_FAILED_EVENT:
                logger.debug("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                break;
            default:
                break;
        }
    }

    public boolean isSucceed() {
        return succeed;
    }
}
技术分享图片
 



以上是关于oss上传文件进度条展示的主要内容,如果未能解决你的问题,请参考以下文章

使用jquery.form.js实现文件上传及进度条前端代码

TP5+阿里云OSS上传文件第三节,实现淘宝上传商品图片

阿里云 oss 小文件上传进度显示

NSURLSesion 上传视频 展示进度条

将图像上传到 Firebase 存储时如何制作进度条?

vue 上传文件到 阿里云OSS,并获取上传进度