全部产品
阿里云办公

下载文件

更新时间:2018-07-30 23:05:09

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

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

下载到本地文件

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

  1. let OSS = require('ali-oss');
  2. let client = new OSS({
  3. region: '<Your region>',
  4. accessKeyId: '<Your AccessKeyId>',
  5. accessKeySecret: '<Your AccessKeySecret>',
  6. bucket: 'Your bucket name'
  7. });
  8. async function get () {
  9. try {
  10. let result = await client.get('object-key', 'local-file');
  11. console.log(result);
  12. } catch (e) {
  13. console.log(e);
  14. }
  15. }
  16. get();

流式下载

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

  1. let OSS = require('ali-oss');
  2. let fs = require('fs');
  3. let client = new OSS({
  4. region: '<Your region>',
  5. accessKeyId: '<Your AccessKeyId>',
  6. accessKeySecret: '<Your AccessKeySecret>',
  7. bucket: 'Your bucket name'
  8. });
  9. async function getStream () {
  10. try {
  11. let result = await client.getStream('object-key');
  12. console.log(result);
  13. let writeStream = fs.createWriteStream('local-file');
  14. result.stream.pipe(writeStream);
  15. } catch (e) {
  16. console.log(e);
  17. }
  18. }
  19. getStream()

下载Buffer

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

  1. let OSS = require('ali-oss');
  2. let client = new OSS({
  3. region: '<Your region>',
  4. accessKeyId: '<Your AccessKeyId>',
  5. accessKeySecret: '<Your AccessKeySecret>',
  6. bucket: 'Your bucket name'
  7. });
  8. async function getBuffer () {
  9. try {
  10. let result = await client.get('object-key');
  11. console.log(result.content);
  12. } catch (e) {
  13. console.log(e);
  14. }
  15. }
  16. getBuffer();

HTTP下载

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

  1. let OSS = require('ali-oss');
  2. let client = new OSS({
  3. region: '<Your region>',
  4. accessKeyId: '<Your AccessKeyId>',
  5. accessKeySecret: '<Your AccessKeySecret>',
  6. bucket: 'Your bucket name'
  7. });
  8. let url = client.signatureUrl('object-key');
  9. console.log(url);
  10. let url = client.signatureUrl('object-key', {expires: 3600});
  11. console.log(url);
  12. // signed URL for PUT
  13. let url = client.signatureUrl('object-key', {method: 'PUT'});
  14. console.log(url);
本文导读目录