const { Storage } = require("@google-cloud/storage");
function uploadFile(bucketName, filePath, destFileName) {
return new Promise(async (resolve, reject) => {
try {
const storage = new Storage({ keyFilename: `${__dirname}/../服務帳戶.json` });
const options = {
destination: destFileName,
preconditionOpts: { ifGenerationMatch: 0 },
// ifGenerationMatch 0 時如果上傳的檔案重複,會出錯
// 因為 Cloud Storage 上名稱相同重複上傳會覆蓋
};
await storage.bucket(bucketName).upload(filePath, options);
resolve({
success: true,
bucketName,
filePath,
});
} catch (error) {
reject(error);
}
});
}
module.exports = {
uploadFile,
};