1. 程式人生 > >oss上傳檔案進度條展示

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;
    }
}