Android接亚马逊s3存储设置上传文件头部信息,文件可直接下载

项目build.gradle添加配置:

implementation "com.amazonaws:aws-android-sdk-s3:2.22.1"
implementation ("com.amazonaws:aws-android-sdk-mobile-client:2.22.1") { transitive = true }

新建Util类:

public class Util {
    private static final String TAG = Util.class.getSimpleName();

    private static AmazonS3Client sS3Client;
    private static AWSCredentialsProvider sMobileClient;
    private static TransferUtility sTransferUtility;

    /**
     * Gets an instance of AWSMobileClient which is
     * constructed using the given Context.
     *
     * @param context Android context
     * @return AWSMobileClient which is a credentials provider
     */
    private static AWSCredentialsProvider getCredProvider(Context context) {
        if (sMobileClient == null) {
            final CountDownLatch latch = new CountDownLatch(1);
            AWSMobileClient.getInstance().initialize(context, new Callback<UserStateDetails>() {
                @Override
                public void onResult(UserStateDetails result) {
                    latch.countDown();
                }

                @Override
                public void onError(Exception e) {
                    latch.countDown();
                }
            });
            try {
                latch.await();
                sMobileClient = AWSMobileClient.getInstance();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return sMobileClient;
    }

    /**
     * Gets an instance of a S3 client which is constructed using the given
     * Context.
     *
     * @param context Android context
     * @return A default S3 client.
     */
    public static AmazonS3Client getS3Client(Context context) {
        if (sS3Client == null) {
            try {
                String regionString = new AWSConfiguration(context)
                        .optJsonObject("S3TransferUtility")
                        .getString("Region");
                Region region = Region.getRegion(regionString);
                sS3Client = new AmazonS3Client(getCredProvider(context), region);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return sS3Client;
    }

    /**
     * Gets an instance of the TransferUtility which is constructed using the
     * given Context
     *
     * @param context Android context
     * @return a TransferUtility instance
     */
    public static TransferUtility getTransferUtility(Context context) {
        if (sTransferUtility == null) {
            sTransferUtility = TransferUtility.builder()
                    .context(context)
                    .s3Client(getS3Client(context))
                    .awsConfiguration(new AWSConfiguration(context))
                    .build();
        }

        return sTransferUtility;
    }

    /**
     * Converts number of bytes into proper scale.
     *
     * @param bytes number of bytes to be converted.
     * @return A string that represents the bytes in a proper scale.
     */
    public String getBytesString(long bytes) {
        String[] quantifiers = new String[]{
                "KB", "MB", "GB", "TB"
        };
        double speedNum = bytes;
        for (int i = 0; ; i++) {
            if (i >= quantifiers.length) {
                return "";
            }
            speedNum /= 1024;
            if (speedNum < 512) {
                return String.format(Locale.US, "%.2f", speedNum) + " " + quantifiers[i];
            }
        }
    }
}

在Activity 的onCreate方法中获取TransferUtility对象

TransferUtility transferUtility = Util.getTransferUtility(this);

设置头部信息主要代码:

if (metadata == null) {
    metadata = new ObjectMetadata();
    metadata.setContentType(MIMETYPE_OCTET_STREAM);//设置头部信息
}

完整代码如下

private void upload(File file, String awsFilePath) {
    if (metadata == null) {
        metadata = new ObjectMetadata();
        metadata.setContentType(MIMETYPE_OCTET_STREAM);//设置头部信息
    }
    TransferObserver observer = transferUtility.upload(
            awsFilePath,
            file,
            metadata
    );
    observer.setTransferListener(new UploadListener(new OnUploadListener() {
        @Override
        public void onStateChanged(int id, TransferState newState) {
                
        }

        @Override
        public void onError(int id, Exception e) {
            
        }
    }));
}
public class UploadListener implements TransferListener {

    private final OnUploadListener mOnUploadListener;

    public UploadListener(OnUploadListener listener) {
        mOnUploadListener = listener;
    }

    // Simply updates the UI list when notified.
    @Override
    public void onError(int id, Exception e) {
        if (mOnUploadListener != null) {
            mOnUploadListener.onError(id, e);
        }
    }

    @Override
    public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
    }

    @Override
    public void onStateChanged(int id, TransferState newState) {
        if (newState == TransferState.COMPLETED) {
            if (mOnUploadListener != null) {
                mOnUploadListener.onStateChanged(id, newState);
            }
        }
    }
}
public interface OnUploadListener {

    void onStateChanged(int id, TransferState newState);

    void onError(int id, Exception e);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java语言实现批量上传文件AWS S3存储的示例代码: ```java import java.io.File; import java.util.List; import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.PutObjectRequest; public class S3Util { private static final String S3_ENDPOINT = "your-s3-endpoint-url"; private static final String S3_REGION = "your-s3-region"; private static final String S3_ACCESS_KEY = "your-s3-access-key"; private static final String S3_SECRET_KEY = "your-s3-secret-key"; private static final String S3_BUCKET_NAME = "your-s3-bucket-name"; public static void uploadFiles(List<File> files) { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(S3_ENDPOINT, S3_REGION)) .withCredentials(new DefaultAWSCredentialsProviderChain()) .build(); try { for (File file : files) { String key = file.getName(); PutObjectRequest request = new PutObjectRequest(S3_BUCKET_NAME, key, file); s3Client.putObject(request); } } catch (AmazonServiceException e) { e.printStackTrace(); } catch (SdkClientException e) { e.printStackTrace(); } } } ``` 使用时,只需传入需要上传的文件列表即可: ```java List<File> files = new ArrayList<>(); files.add(new File("file1")); files.add(new File("file2")); S3Util.uploadFiles(files); ``` 在上述代码中,我们使用了AWS SDK的`AmazonS3`客户端,通过`withEndpointConfiguration`方法设置S3的Endpoint URL和Region,`withCredentials`方法设置S3的Access Key和Secret Key,`build`方法创建S3客户端。在上传文件时,我们使用了`PutObjectRequest`对象,其中包含了需要上传的文件存储桶名称和对象名称,通过`putObject`方法将文件上传到S3存储中。 希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值