node腾讯云对象存储 文件上传

对象存储 文件上传

# npm i qcloud-cos-sts --save

var STS = require('qcloud-cos-sts');
// 配置参数
var config = {
  secretId: 'AKIDb2D8mAI9j36sNbYEdlcCWZLq65nLbaIk',   //修改
  secretKey: 'C7l9G6ewxhBOL1QYQ1KM8droUu3vWtzo', //修改
  proxy: '',
  durationSeconds: 1800,

  // 放行判断相关参数
  bucket: 'yanxianfei-1307931282',  //修改
  region: 'ap-beijing',  //修改
  allowPrefix: '*', // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  // 简单上传和分片,需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
  allowActions: [
      // 简单上传
      'name/cos:PutObject',
      'name/cos:PostObject',
      // 分片上传
      'name/cos:InitiateMultipartUpload',
      'name/cos:ListMultipartUploads',
      'name/cos:ListParts',
      'name/cos:UploadPart',
      'name/cos:CompleteMultipartUpload'
  ],
};

// 腾讯云生成临时秘钥

// 创建临时密钥服务
var app = express();
app.use(bodyParser.json());

// 支持跨域访问
app.all('*', function (req, res, next) {
  res.header('Content-Type', 'application/json');
  res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:88');
  res.header('Access-Control-Allow-Headers', 'origin,accept,content-type');
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method.toUpperCase() === 'OPTIONS') {
      res.end();
  } else {
      next();
  }
});
// 临时密钥接口
app.all('/sts', function (req, res, next) {

  // TODO 这里根据自己业务需要做好放行判断

  // 获取临时密钥
  var shortBucketName = config.bucket.substr(0 , config.bucket.lastIndexOf('-'));
  var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
  var policy = {
      'version': '2.0',
      'statement': [{
          'action': config.allowActions,
          'effect': 'allow',
          'principal': {'qcs': ['*']},
          'resource': [
              'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
          ],
      }],
  };
  STS.getCredential({
      secretId: config.secretId,
      secretKey: config.secretKey,
      proxy: config.proxy,
      durationSeconds: config.durationSeconds,
      policy: policy,
  }, function (err, tempKeys) {
      var result = JSON.stringify(err || tempKeys) || '';
      res.send(result);
  });
});

# 请求/sts接口 返回秘钥
![image.png](https://upload-images.jianshu.io/upload_images/24202745-6c5b1dc035eca137.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

html 上传示例




     ZTREE DEMO - beforeCheck / onCheck
    

    
    


    





你可能感兴趣的:(node腾讯云对象存储 文件上传)