簡體   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