首页 > 解决方案 > 将内容保存在 Google 存储文件中

问题描述

我尝试通过 Nodejs 将生成的文件从内存中的 JSON 保存到谷歌存储。

GCS 的保存过程运行良好,它正在创建文件,但它的抛出错误。(该过程有效,因为我没有发现错误)。

据我了解,错误来自storage.bucket(bucket).file(filename)

我怎样才能避免异常?

   let file = storage.bucket('dev').file('widgets/test.json');
   file.setMetadata({
        contentType: contentType,',
        cacheControl: 'public,no-cache,max-age=0',
    });
    return await file.save(json.stringify(content))`

错误 - UnhandledPromiseRejectionWarning: Error: No such object: dev/widgets/test.json

标签: node.jsgoogle-apigoogle-cloud-storagegoogle-api-nodejs-client

解决方案


我遇到了同样的错误,经过一段时间后,我找到了一种传递 contentType 的方法。我希望有一天它会对某人有所帮助!

        // upload the file
        var idsObj = {"ids": ids};
        var idsJSONStr = JSON.stringify(idsObj); // convert object to json string

        const file = storage
            .bucket(bucketName)
            .file(fileName);

        const isSaved = await file.save(idsJSONStr, {
            contentType: 'application/json'
        }).then(function(err) {
            if (err && err.length != 0) {
                console.error("The file is not saved", err);
                return false;
            } else {
                return true;
            }
        });

        console.log('The file is saved: ', isSaved);
  

推荐阅读