繁体   English   中英

App Engine node.js标准环境下如何下载json文件到云存储

[英]How to download json file to cloud storage on app engine node.js standard environment

我在 GAE node.js 标准环境上有一个 web 应用程序。 服务器收到一个 POST 请求,其正文中包含 json(未准备好 json 文件)。 我想将这个 json 文件写入 Cloud Storage。 这该怎么做?

您必须获取正文(JSON)并将其保存在云存储文件中。 这应该足够了

要使用您的帖子请求的正文,您可以在此处查看之前的讨论。 另一方面,如果您特别想将其转换为 JSON 文件,请查看此其他帖子 继续上传,您可以参考文档示例,这是建议的过程(请访问页面以获取推荐变量路径的完整脚本以及指向 Cloud Storage Node.js API 参考的链接):

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function uploadFile() {
  await storage.bucket(bucketName).upload(filePath, {
    destination: destFileName,
  });

  console.log(`${filePath} uploaded to ${bucketName}`);
}

uploadFile().catch(console.error);

您需要使用fs.createWriteStream将 JSON 文件写入/tmp目录,然后使用 Storage API 将其写入 Storage

关键是使用req.rawBody而不是req.body 这是一个完整的工作示例:

exports.getData = (req, res) => {

// The ID of your GCS bucket
const bucketName = 'yourBucket';
// The new ID for your GCS file
const destFileName = 'yourFileName';
// The content to be uploaded in the GCS file
const contents = req.rawBody;
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Import Node.js stream
const stream = require('stream');
// Creates a client
const storage = new Storage();
// Get a reference to the bucket
const myBucket = storage.bucket(bucketName);
// Create a reference to a file object
const file = myBucket.file(destFileName);

// Create a pass through stream from a string
const passthroughStream = new stream.PassThrough();
passthroughStream.write(contents);
passthroughStream.end();

async function streamFileUpload() {
  passthroughStream.pipe(file.createWriteStream()).on('finish', () => {
    res.status(200).send('OK');
  });

  console.log(`${destFileName} uploaded to ${bucketName}`);
}

streamFileUpload().catch(console.error);

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM