我正在编写代码,使用gcloud-node将使用node-fetch获取的文件上传到Google云端存储中的存储区。
到目前为止一切正常,但我在查找如何在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);
}
});
}
答案 0 :(得分:8)
事实证明,文件中有一个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);
}
});
}