实践背景
对象存储SDK提供预签名接口可以生成预签名URL,通过预签名URL,移动端APP可以直接上传或者下载文件。不需要使用SDK和密钥,使用HTTP接口就可以进行文件的上传和下载。
应用流程
使用预签名URL直传媒体存储应用流程如下:
实践步骤
生成预签名URL
业务服务器配置长期密钥,调用预签名接口生成预签名URL,具体可参照如下java示例。如需其他语言SDK 示例,可参考:SDK概览 。
- 上传预签名
String bucketName = "<your-bucket-name>";
String objectKey = "<your-object-key>";
LocalDateTime expirationDateTime = LocalDateTime.now().plusSeconds(5 * 60); //url的有效时间5分钟
Date expiration = Date.from(expirationDateTime.atZone(ZoneId.systemDefault()).toInstant());
try {
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
URL url = s3.generatePresignedUrl(generatePresignedUrlRequest);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
}
- 下载预签名
String bucketName = "<your-bucket-name>";
String objectKey = "<your-object-key>";
try {
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
URL url = s3.generatePresignedUrl(generatePresignedUrlRequest);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
}
使用预签名URL直传
移动端通过业务服务器获取到预签名URL,使用HTTP接口和预签名URL上传或者下载文件。具体可参照如下示例。
- 上传
Log.i(TAG, "upload");
try {
OkHttpClient httpClient = new OkHttpClient.Builder()
.followRedirects(false)
.retryOnConnectionFailure(false)
.cache(null)
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create("file content", mediaType);
Request httpRequest = new Request.Builder()
.url(url)
.put(body)
.build();
Call c = httpClient.newCall(httpRequest);
Response res = c.execute();
Log.i(TAG, "Status:" + res.code());
if (res.header("ETag") != null) {
Log.i(TAG, "ETag:" + res.header("ETag"));
}
res.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 下载
private void download(String url) {
Log.i(TAG, "download");
try {
OkHttpClient httpClient = new OkHttpClient.Builder()
.followRedirects(false)
.retryOnConnectionFailure(false)
.cache(null)
.build();
Request httpRequest = new Request.Builder()
.url(url)
.get()
.build();
Call c = httpClient.newCall(httpRequest);
Response res = c.execute();
Log.i(TAG, "Status:" + res.code());
if (res.body() != null) {
Log.i(TAG, "Content:" + res.body().string());
}
res.close();
} catch (IOException e) {
e.printStackTrace();
}
}