GCP Cloud Storage:bucket.upload 和 file.save 方法有什么区别?

sam*_*er1 3 node.js google-cloud-storage google-cloud-platform

有更好的上传文件的选择吗?

就我而言,我需要上传很多小文件(pdf 或文本),我必须决定最佳选择,但是无论如何这两种方法之间有区别吗?

这里有两个例子直接取自文档

保存方法:(文档

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';

file.save(contents, function(err) {
  if (!err) {
    // File written successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});
Run Code Online (Sandbox Code Playgroud)

上传方式:(文档

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Upload a file from a local path.
//-
bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
  // Your bucket now contains:
  // - "image.png" (with the contents of `/local/path/image.png')

  // `file` is an instance of a File object that refers to your new file.
});
Run Code Online (Sandbox Code Playgroud)

小智 5

从本质上讲,这两个函数都做同样的事情。他们将文件上传到存储桶。一个只是 上的函数bucket,另一个是 上的函数file。他们最终都跟注file.createWriteStream,所以他们也有相同的表现。

这些函数在上传类型方面的行为有所不同。file.save除非您另外指定,否则将默认为可恢复上传(您可以将resumable布尔值设置SaveOptions为 false)。bucket.upload如果文件小于 5MB,则执行分段上传,否则执行断点续传。例如,您可以通过修改上的布尔值bucket.upload来强制进行可恢复上传或分段上传。resumableUploadOptions

请注意,在即将发布的主要版本中(https://github.com/googleapis/nodejs-storage/pull/1876),此行为将被统一。无论文件大小如何,这两个函数都将默认为可断点续传。行为将是相同的。

对于小文件,建议分段上传。