

喜讯:国内、香港、海外云服务器租用特惠活动,2核/4G/10M仅需31元每月,点击抢购>>>
点击这里注册天翼云特邀VIP帐号,立即体验天翼云对象存储>>>
使用预签名URL直传天翼云对象存储(融合版)教程
实践背景
对象存储SDK提供预签名接口可以生成预签名URL,通过预签名URL,移动端APP可以直接上传或者下载文件。不需要使用SDK和密钥,使用Http接口就可以进行文件的上传和下载。
应用流程
使用预签名URL直传对象存储(融合版)应用流程如下:

实践步骤
生成预签名URL
业务服务器配置长期密钥,调用预签名接口生成预签名URL,具体可参照如下java示例。
上传预签名
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();
}
}推荐:TOP云智能建站优惠活动,仅880元即可搭建一个后台管理五端合一的智能网站(PC网站、手机网站、百度智能小程序、微信小程序、支付宝小程序),独享百度搜索SEO优势资源,让你的网站不仅有颜值有排面,更有排名,可以实实在在为您带来效益,请点击进入TOP云智能建站>>>,或咨询在线客服了解详情。


湘公网安备43019002001857号
备案号:
客服1