How to use ali-oss - 10 common examples

To help you get started, we’ve selected a few ali-oss examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aliyun / serverless-aliyun-function-compute / test / project / src / ossTriggerHandler.js View on Github external
module.exports = (event, context, callback) => {
  const parsedEvent = JSON.parse(event);
  const ossEvent = parsedEvent.events[0];
  // Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai"
  const ossRegion = `oss-${ossEvent.region}`;
  // Create oss client.
  const client = new oss({
    region: ossRegion,
    bucket: ossEvent.oss.bucket.name,
    // Credentials can be retrieved from context
    accessKeyId: context.credentials.accessKeyId,
    accessKeySecret: context.credentials.accessKeySecret,
    stsToken: context.credentials.securityToken
  });

  const objKey = ossEvent.oss.object.key;
  console.log('Getting object: ', objKey);
  client.get(objKey).then(function(val) {
    const newKey = objKey.replace('source/', 'processed/');
    return client.put(newKey, val.content).then(function (val) {
      console.log('Put object:', val);
      callback(null, val);
    }).catch(function (err) {
github Alex1990 / tiny-oss / test / server.js View on Github external
app.use(async (ctx, next) => {
  lastReqTime = Date.now();
  if (ctx.path === '/api/oss-config') {
    ctx.body = {
      accessKeyId,
      accessKeySecret,
      bucket,
      region,
      endpoint,
    };
  }
  if (ctx.path === '/api/sts') {
    const sts = new STS({
      accessKeyId,
      accessKeySecret,
    });
    // 60 mins
    const expires = 60 * 60;
    const sessionName = 'foo';
    const stsToken = await sts.assumeRole(arn, undefined, expires, sessionName);
    ctx.body = {
      bucket,
      region,
      endpoint,
      stsToken,
    };
  }
  next();
});
github yedaodao / hexo-deployer-aliyun / lib / deployer.js View on Github external
'Example:',
            '  deploy:',
            '    type: aliyun',
            '    bucket: yourBucketName',
            '    region: yourOSSregion',
            '    accessKeyId: yourAccessKeyId',
            '    accessKeySecret: yourAccessKeySecret',
            '',
            'For more help, you can check the docs: ' + chalk.underline('http://hexo.io/docs/deployment.html') + ' and ' + chalk.underline('https://help.aliyun.com/document_detail/31867.html?spm=5176.doc31950.2.1.WMtDHS')
        ];
        console.log(help.join('\n'));
        log.error('config error');
        return;
    }

    var client = new OSS({
        region: args.region,
        accessKeyId: args.accessKeyId,
        accessKeySecret: args.accessKeySecret,
        bucket: args.bucket
    });

    log.info('Uploading files to Aliyun...');

    // get all files sync
    traverseFiles(publicDir, function (file) {
        uploadFileList.push({
            uploadPath: getUploadPath(file, pathFn.basename(publicDir)),
            file: file
        });
    });
github gzgogo / antd-pro-mobx / src / component / OSSUpload / index.js View on Github external
customRequest = async (option) => {
    this.setState({
      loading: true
    });

    const res = await getSTS();

    if (res && res.code === 0 && res.data) {
      const client = new OSS({
        ...res.data,
        expire: ''
      });

      // const fileName = `upload/${shortid.generate()}${getFileExt(option.file.name)}`;
      const fileName = `${shortid.generate()}${getFileExt(option.file.name)}`;
      const result = await client.put(fileName, option.file);

      if (result.res && result.res.status === 200) {
        option.onSuccess(result);
      } else {
        option.onError(result);
      }
    } else {
      console.error('请实现自己的STS接口,详情可参考 https://help.aliyun.com/document_detail/32077.html?spm=a2c4g.11186623.6.788.qrBaau');
    }
github mdnice / markdown-nice / src / utils / imageHosting.js View on Github external
const aliOSSPutObject = ({config, file, buffer, onSuccess, onError, images, content}) => {
  let client;
  try {
    client = new OSS(config);
  } catch (error) {
    message.error("OSS配置错误,请根据文档检查配置项");
    return;
  }

  const OSSName = getOSSName(file.name);

  client
    .put(OSSName, buffer)
    .then((response) => {
      const names = file.name.split(".");
      names.pop();
      const filename = names.join(".");
      const image = {
        filename, // 名字不变并且去掉后缀
        url: response.url,
github dzy321 / file-upload / lib / oss.js View on Github external
// {
  //    accessKeyId:     "keyId",
  //    accessKeySecret: "secret",
  //    bucket:          "terminus-designer",
  //    region:          "oss-cn-hangzhou"
  // }
  let { accessKeyId, accessKeySecret, bucket, region, targetProtocol, attachment, targetHost } = options

  if (!targetHost) {
    targetHost = `${bucket}.${region}.aliyuncs.com`
  }

  if (!(accessKeyId && accessKeySecret && bucket && region)) {
    throw new Error("Missing option in options: [accessKeyId, accessKeySecret, bucket, region]")
  }
  const store = new oss(options)

  return {
    put: async (filename, file) => {
      await util.fileResolve(file)
      const opts = attachment === true ? {
        headers: {
          "Content-Disposition": `attachment;filename=${encodeURIComponent(file.filename)};filename*=UTF-8''${encodeURIComponent(file.filename)}`
        }
      } : undefined
      return store.put(filename, file.path, opts)
    },
    get: (result) => {
      Object.keys(result).map(filename => {
        return result[filename] = `${targetProtocol ? `${targetProtocol}:` : ""}//${targetHost}/${result[filename]}`
      })
      return result
github LTTPP / know / Wit / alicloud / ali.services.auth.js View on Github external
function kv(key, callback) {
    const ossclient = new OSS({
        region: 'oss-cn-beijing',
        accessKeyId: accessKeyId,
        accessKeySecret: accessKeySecret,
        bucket: bucket
    });

    ossclient.get(key).then(function (res) {
        const value = res.content; // plain text
        if (isValidToken(value.toString())) {
            callback(null, value);
        } else {
            renew((newValue) => { // plain text
                // process expires_in value
                const v = normalize(newValue); // JSON object
                // refresh the OOS
                ossclient.put(key, Buffer.from(stringify(v))); // buffer type
github awesomes-cn / api / lib / aliyun.js View on Github external
var OSS = require('ali-oss')

var localEnv = require('../config')
const request = require('request')

var client = new OSS.Wrapper({
  region: localEnv.alioss.region,
  accessKeyId: localEnv.alioss.AccessKeyId,
  accessKeySecret: localEnv.alioss.AccessKeySecret
})

var aliyun = {
  // 上传普通文件
  upload: async (file, filename) => {
    client.useBucket(localEnv.alioss.bucket)
    return await client.put(filename, file)
  },

  // 上传网络图片
  uploadUrl: async (url, filename) => {
    var stream = require('stream')
    var a = new stream.PassThrough()
github bimohxh / webon / lib / aliyun.js View on Github external
var OSS = require('ali-oss')
var Helper = require('./helper')

var localEnv = Helper.readLocalEnv()


const fetchConfVal = (str) => {
  let matchs = str.match(/^<(.+)>$/) 
  return matchs ? process.env[matchs[1]] : str
}

var client = new OSS.Wrapper({
  region: localEnv.aliyun.region,
  accessKeyId: fetchConfVal(localEnv.aliyun.accessKeyId),
  accessKeySecret: fetchConfVal(localEnv.aliyun.accessKeySecret)
})

var aliyun = {
  // 上传
  upload: (file, removePrefix) => {
    return new Promise(resolve => {
      let fullname = Helper.uploadFileName(file, removePrefix)
      client.useBucket(localEnv.aliyun.bucket)
      client.put(fullname, file).then((data) => {
        resolve()
      })
    })
  }
github cloudfoundry-incubator / service-fabrik-broker / test / test_broker / iaas.AliClient.spec.js View on Github external
it('getting container properties should fail with multiple buckets error', function () {
        sandbox.restore();
        sandbox.stub(AliStorage.prototype, 'useBucket').withArgs(settings.container).returns(listFilesStub);
        sandbox.stub(AliStorage.prototype, 'listBuckets').withArgs({ prefix: settings.container }).callsFake(incorrectBucketStub2);
        return client.getContainer()
          .then(() => {
            logger.error('The get container call should fails');
            throw new Error('The get container call should fails');
          })
          .catch(err => {
            expect(err.message).to.equal(`More than 1 Buckets with prefix ${settings.container} exists`);
          });
      });

ali-oss

aliyun oss(object storage service) node client

MIT
Latest version published 3 months ago

Package Health Score

82 / 100
Full package analysis