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



我正在编写一段代码,该代码使用gcloud节点将使用node fetch获取的文件上传到谷歌云存储中的存储桶中。

到目前为止,一切都正常,但我很难找到如何在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);
    }
  });
}

相关内容

  • 没有找到相关文章

最新更新