Overview
The Object Storage Service (OSS) software development kit (SDK) provides functions to sign, upload, and download objects. However, you may sometimes need to use the API directly to perform these actions with a signature. This topic provides a Node.js example of how to use the PutObject operation to upload an object with a signed header.
Note
Use the OSS SDK when possible. The example in this topic only shows how to implement a signed upload. You must modify the code to suit your business needs.
Details
The following code shows how to use the PutObject operation in Node.js v12.10.0.
Note
This example requires the crypto-js and request modules.
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';
// Generate the GMT date.
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 );
});
References
Include a signature in the header
Applies to
-
Object Storage Service (OSS)