1. 程式人生 > >oss上傳文件進度條展示

oss上傳文件進度條展示

nta 監聽 rac 整理 沒有 ger idg unknown amp

用戶上傳文件至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上傳文件進度條展示