概述
OSS的集成上传和下载提供了SDK可以直接使用,但实际使用中一些用户受限环境或者设备限制需要使用api方式来实现上传和下载,本文以PutObject接口为例,提供了NodeJS实现的demo。
注:建议优先使用OSS提供SDK,本文提供的只是签名实现上传demo,实际使用中需要结合业务来进行改动代码
详细信息
PutObject实现demo(测试环境Node.js v12.10.0,所需模块crypto-js、request):
var HmacSha1 = require('crypto-js/hmac-sha1') ;
var Base64 = require('crypto-js/enc-base64');
var request = require("request");
//endpoint
var endpont = 'http://oss-cn-hangzhou.aliyuncs.com';
//bucket
var bucketName = 'xxx';
//objectname
var objectname= 'mytest/nodejs.txt';
//accesskey
var accesskey = 'xxxx';
//accesskeySecret
var accesskeysecret ='xxx';
//生成GMT时间
var gmtDate = (new Date()).toGMTString();
console.log(gmtDate);
var contenttype = 'application/json';
var strtosgin = 'PUT\n\n'+contenttype+'\n'+gmtDate+'\n'+'/'+bucketName+'/'+objectname
var sign = Base64.stringify((HmacSha1(strtosgin,accesskeysecret)));
var options = {
url: 'http://xxx.oss-cn-hangzhou.aliyuncs.com/'+objectname,
headers: {
'Content-Type':contenttype,
'Date':gmtDate,
'Authorization': 'OSS '+accesskey+':'+sign
},
body:'{test:test}'
};
request.put(options, function(error, response, body) {
console.info('response:' + JSON.stringify(response));
console.info("statusCode:" + response.statusCode)
console.info('body: ' + body );
});