好处:使用OSS经过签名的URL上传文件,无需经过ECS云服务器,省了流量和带宽
首先:更新java开发包
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体]Java SDK开发包(2015-01-15) 版本号 2.0.1。说明,老版本的开发包生成的URL不能拿来直接上传文件。总是提示签名错误(403,SingatureDoesNotMatch
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体])
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体]。
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体]第二步,生成经过签名的URL
/** QQ:798255396
* 生成上传文件的URL
* @param key 文件的object key,自己定义
* @return URL
*/
public URL getPutUrl(String key){
//初始化OSSClient
OSSClient clientOut = new OSSClient(endpoint, accessKeyId, accessKeySecret);
clientOut .createBucket(bucketName);
//设置有效期
Date expiration = new Date(new Date().getTime() + 3600 * 9000);
// 创建请求
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
generatePresignedUrlRequest.setBucketName(bucketName);
// HttpMethod为PUT
generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
generatePresignedUrlRequest.setExpiration(expiration);
//必须有
generatePresignedUrlRequest.setContentType("image/jpeg");
// 生成签名的URL
URL url = this.clientOut.generatePresignedUrl(generatePresignedUrlRequest)
return url;
}
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体]第三步,用
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体]HttpPut
[font=微软雅黑, 'Microsoft Yahei', 'Hiragino Sans GB', tahoma, arial, 宋体]上传Object
/**
*
* @param url 第二步生成的签名url
* @param filename 文件名称
* @param filepath 文件路径
*/
public void SubmitPut(String url,String filename, String filepath){
HttpClient httpclient = new DefaultHttpClient();
try {
//必须用HttpPut ,不能用HttpPost。因为OSS拒绝Post请求
HttpPut httpput = new HttpPut(url);
FileBody bin = new FileBody(new File(filepath + File.separator + filename));
httpput.addHeader("Content-Type", "image/jpeg");
StringBody ResourceType = new StringBody("Object");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("ResourceType",ResourceType);
reqEntity.addPart("key", bin);//
httpput.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpput);
StatusLine statusLine = response.getStatusLine();
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
System.out.println("服务器正常响应.....");
HttpEntity resEntity = response.getEntity();
System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
EntityUtils.consume(resEntity);
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.getConnectionManager().shutdown();
} catch (Exception ignore) {
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。