本文介绍如何下载文件。

用户可以通过以下方式从OSS中下载文件:

  • 下载到本地文件
  • 流式下载
  • 下载到Buffer
  • HTTP下载(浏览器下载)

下载到本地文件

通过get接口来下载Object到一个本地文件:

let OSS = require('ali-oss');

let client = new OSS({
  region: '<Your region>',
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: 'Your bucket name'
});

async function get () {
  try {
    let result = await client.get('object-name', 'local-file');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

get();

流式下载

使用getStream来下载文件时,返回一个Readable Stream,用户可以流式地 处理文件内容。

let OSS = require('ali-oss');
let fs = require('fs');

let client = new OSS({
  region: '<Your region>',
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: 'Your bucket name'
});

async function getStream () {
  try {
    let result = await client.getStream('object-name');
    console.log(result);
    let writeStream = fs.createWriteStream('local-file');
    result.stream.pipe(writeStream);
  } catch (e) {
    console.log(e);
  }
}

getStream()

下载Buffer

用户也可以通过get接口简单地将文件内容下载到Buffer中:

let OSS = require('ali-oss');

let client = new OSS({
  region: '<Your region>',
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: 'Your bucket name'
});

async function getBuffer () {
  try {
    let result = await client.get('object-name');
    console.log(result.content);
  } catch (e) {
    console.log(e);
  }
}

getBuffer();

HTTP下载

对于存放在OSS中的文件,在不用SDK的情况下用户也可以直接使用HTTP下载,这 包括直接使用浏览器下载,或者使用wget, curl等命令行工具下载。这时文 件的URL需要由SDK生成。使用signatureUrl方法生成可下载的HTTP地址,URL 的有效时间默认为半个小时:

let OSS = require('ali-oss');

let client = new OSS({
  region: '<Your region>',
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: 'Your bucket name'
});

let url = client.signatureUrl('object-name');
console.log(url);

let url = client.signatureUrl('object-name', {expires: 3600});
console.log(url);

// signed URL for PUT
let url = client.signatureUrl('object-name', {method: 'PUT'});
console.log(url);