使用AWS S3签名网址获取上传进度

时间:2016-06-20 03:40:56

标签: amazon-web-services amazon-s3 upload

我正在制作一个应用程序,让用户可以使用AWS S3将视频上传到我们的最终端。我使用服务器生成签名的URL并将其返回给客户端(Web浏览器),然后客户端使用该URL上传到我们的后端。它工作得很好,但我有一个小问题,我们无法跟踪从浏览器开始的文件上传进度。

那么我们有什么方法可以从我们的服务器获得上传的进展吗?

1 个答案:

答案 0 :(得分:0)

相同的Java代码段

public void uploadtoS3(File file) throws AmazonServiceException, AmazonClientException, InterruptedException {
        logger.debug("Uploading the File => S3");
        ProfileCredentialsProvider credentialProviderChain = new ProfileCredentialsProvider();
        TransferManager tx = new TransferManager(credentialProviderChain.getCredentials());
        final Upload upload = tx.upload(env.getProperty("amazon.s3.media.bucket"), file.getName(), file);

        // You can poll your transfer's status to check its progress
        if (upload.isDone() == false) {
            logger.debug("Transfer: " + upload.getDescription());
            logger.debug("State: " + upload.getState());
            logger.debug("Progress: " + upload.getProgress().getBytesTransferred());
        }

        // Transfers also allow you to set a <code>ProgressListener</code> to
        // receive
        // asynchronous notifications about your transfer's progress.

        upload.addProgressListener(new ProgressListener() {
            // This method is called periodically as your transfer progresses
            public void progressChanged(ProgressEvent progressEvent) {
                logger.debug(upload.getProgress().getPercentTransferred() + "%");

                if (progressEvent.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE) {
                    logger.debug("Upload complete!!!");
                }
            }
        });

        // Or you can block the current thread and wait for your transfer to
        // to complete. If the transfer fails, this method will throw an
        // AmazonClientException or AmazonServiceException detailing the reason.
        upload.waitForCompletion();

        // After the upload is complete, call shutdownNow to release the
        // resources.
        tx.shutdownNow();
    }

也适用于MultiPart上传。