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;
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用阿里云的Java SDK来实现OSS文件下载,并且通过多线程和进度条来显示下载进度。以下是一个示例代码: ``` import com.aliyun.oss.OSS; import com.aliyun.oss.event.ProgressEvent; import com.aliyun.oss.event.ProgressEventType; import com.aliyun.oss.event.ProgressListener; import com.aliyun.oss.model.GetObjectRequest; import com.aliyun.oss.model.OSSObject; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class OSSDownloadWithProgress { private static final String ACCESS_KEY_ID = "<yourAccessKeyId>"; private static final String ACCESS_KEY_SECRET = "<yourAccessKeySecret>"; private static final String ENDPOINT = "<yourEndpoint>"; private static final String BUCKET_NAME = "<yourBucketName>"; private static final String OBJECT_KEY = "<yourObjectKey>"; private static final String DOWNLOAD_FILE_NAME = "<yourDownloadFileName>"; private static final int THREAD_POOL_SIZE = 5; public static void main(String[] args) { // 创建OSSClient实例 OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET); // 创建线程池 ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); // 创建GetObjectRequest对象并设置进度监听器 GetObjectRequest getObjectRequest = new GetObjectRequest(BUCKET_NAME, OBJECT_KEY); getObjectRequest.setProgressListener(new ProgressListener() { private long bytesWritten = 0; private long totalBytes = -1; private boolean succeed = false; @Override public void progressChanged(ProgressEvent progressEvent) { long bytes = progressEvent.getBytes(); ProgressEventType eventType = progressEvent.getEventType(); switch (eventType) { case TRANSFER_STARTED_EVENT: System.out.println("Start to download..."); break; case RESPONSE_CONTENT_LENGTH_EVENT: this.totalBytes = bytes; System.out.println(this.totalBytes + " bytes in total will be downloaded to a local file"); break; case RESPONSE_BYTE_TRANSFER_EVENT: this.bytesWritten += bytes; if (this.totalBytes != -1) { int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes); System.out.println(bytes + " bytes have been written at this time, download progress: " + percent + "% (" + this.bytesWritten + "/" + this.totalBytes + ")"); } else { System.out.println(bytes + " bytes have been written at this time, download ratio: unknown" + "(" + this.bytesWritten + "/...)"); } break; case TRANSFER_COMPLETED_EVENT: this.succeed = true; System.out.println("Succeed to download, " + this.bytesWritten + " bytes have been transferred in total"); break; case TRANSFER_FAILED_EVENT: System.out.println("Failed to download, " + this.bytesWritten + " bytes have been transferred"); break; default: break; } } }); // 提交下载任务到线程池 executorService.submit(() -> { try { // 下载OSS文件到本地 OSSObject ossObject = ossClient.getObject(getObjectRequest); BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent()); File file = new File(DOWNLOAD_FILE_NAME); FileOutputStream out = new FileOutputStream(file); byte[] buffer = new byte[8192]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭OSSClient和线程池 ossClient.shutdown(); executorService.shutdown(); } }); } } ``` 在上面的代码中,我们通过创建GetObjectRequest对象并设置进度监听器来实现OSS文件的下载进度显示。然后,我们将下载任务提交到线程池中,并在下载完成后关闭OSSClient和线程池。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值