【问题标题】:Upload Buffer Directly to Google Cloud Storage将缓冲区直接上传到 Google Cloud Storage
【发布时间】:2021-05-22 14:41:26
【问题描述】:

我正在从第三方供应商处以arraybuffer 的形式获取 PDF 文档。我想将 arraybuffer 直接上传到 Google 存储,而不创建文件的本地副本。

const axios = require('axios');
const google_storage = new Storage({ keyFilename: 'path_to_keyFilename' });

const upload_file = async (req, res, next) => {
  try {
    let fetching_result = await axios({
      method: 'get',
      url: 'PDF_document_url',
      responseType: 'arraybuffer'
    });
    let upload_result = await google_storage.bucket('bucket_name').upload(fetching_result.data);
    return res.status(200).json(upload_result.data);
  } catch (error) {
    console.log('ERROR: ', error);
    return res.status(400).json(error);
  }
}

我正在使用@google-cloud/storage 包上传文件。但是当我将arraybuffer 传递给它时,出现以下错误:

错误:TypeError [ERR_INVALID_ARG_VALUE]:参数“路径”必须是不带空字节的字符串或 Uint8Array。 收到

我还尝试将 arraybuffer 转换为 Uint8Array 并通过它,但随后收到以下错误:

错误:TypeError [ERR_INVALID_ARG_VALUE]:参数“路径”必须是不带空字节的字符串或 Uint8Array。 收到 Uint8Array(116107) [ 37, 80, 68, 70, 45, 49, 46, 53, 10, 37, 216, 229 ...

有谁知道这里发生了什么以及如何解决这个问题?

【问题讨论】:

  • 你能提供一个更大的堆栈跟踪吗?
  • 更重要的是,请包含您正在使用的代码。例如。这是在尝试使用Bucket.uploadFile.saveFile.createWriteStream 等吗?
  • 你完全正确。我更新了我的问题。我尝试使用Bucket.upload()

标签: javascript node.js google-api google-cloud-storage google-api-client


【解决方案1】:

bucket.upload() 需要一个文件名作为第一个参数,而不是您尝试保存的实际文件。

File.createWriteStream() 应该会更好:

const myData: Uint8Array = *something*;

const storage = new Storage();
const bucket = storage.bucket("myBucket");

const blob = bucket.file("myFile");
const blobStream = blob.createWriteStream({
    resumable: false,
});

blobStream.end(myData);

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2018-11-18
    • 2017-03-20
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多