如何使用 node.js 为上传到 Google 云存储的文件设置内容类型

How to set the Content-Type for a file being uploaded to Google Cloud Storage using node.js

我正在编写代码,使用 gcloud-node 将使用 node-fetch 获取的文件上传到 Google Cloud Storage 中的存储桶。

到目前为止一切正常,但我无法找到如何为 GCloud 上的文件设置 Content-Type,否则文件将下载为 application/octet-stream

这是我目前的代码:

function saveImage(response, destFile) {
  return new Promise((resolve, reject) => {
    if (response.status !== 200) {
      reject(new Error('Bad Response'));
    }

    // How do I set this on the file uploaded to the bucket?
    const contentType = response.headers.get('Content-Type');

    try {
      const file = bucket.file(destFile);
      const writeStream = file.createWriteStream();

      writeStream.on('error', err => {
        reject(err);
      });

      writeStream.on('finish', () => {
        resolve(getPublicUrl(destFile));
      });

      response.body.pipe(writeStream);
    } catch (e) {
      reject(e);
    }
  });
}

事实证明文件上有一个 setMetadata 方法,您可以调用该方法并将 Content-Type 作为参数传递。工作代码如下所示:

function saveImage(response, destFile) {
  return new Promise((resolve, reject) => {
    if (response.status !== 200) {
      reject(new Error('Bad Response'));
    }

    const contentType = response.headers.get('Content-Type');
    try {
      const file = bucket.file(destFile);

      const writeStream = file.createWriteStream({
        metadata:{
          contentType: contentType
        }
      });

      writeStream.on('error', err => {
        reject(err);
      });

      writeStream.on('finish', () => {
        resolve(getPublicUrl(destFile));
      });

      response.body.pipe(writeStream);
    } catch (e) {
      reject(e);
    }
  });
}