目前,我正在使用@google-cloud/storage NPM軟件包將文件直接上傳到Google雲端存儲存儲分區。這需要一些詭計,因爲我只有圖像的base64編碼字符串。我必須:如何使用Node.js將base64編碼圖像(字符串)直接上傳到Google Cloud Storage存儲桶?
- 解碼字符串
- 另存爲文件
- 發送的文件路徑下面的腳本上傳到谷歌雲存儲
- 刪除本地文件
我想避免將文件存儲在文件系統中,因爲我正在使用Google App Engine,並且如果刪除操作因任何原因而不起作用,我不想超載文件系統/將垃圾文件放在那裏。這是我上傳腳本看起來像現在:
// Convert the base64 string back to an image to upload into the Google Cloud Storage bucket
var base64Img = require('base64-img');
var filePath = base64Img.imgSync(req.body.base64Image, 'user-uploads', 'image-name');
// Instantiate the GCP Storage instance
var gcs = require('@google-cloud/storage')(),
bucket = gcs.bucket('google-cloud-storage-bucket-name');
// Upload the image to the bucket
bucket.upload(__dirname.slice(0, -15) + filePath, {
destination: 'profile-images/576dba00c1346abe12fb502a-original.jpg',
public: true,
validation: 'md5'
}, function(error, file) {
if (error) {
sails.log.error(error);
}
return res.ok('Image uploaded');
});
反正是有直接上傳編碼的圖像,而不必把它轉換成一個文件,然後上傳使用路徑的字符串的base64?
'bucket.upload'封裝了''文件。createWriteStream'函數,因此您需要將base64文件字符串傳送到由'file'中的該方法創建的流中。我建議只需寫入文件系統並在上傳後取消鏈接。我認爲你在刪除文件時會遇到問題。如果你真的喜歡,我可能會舉一個例子。 – forrestmid
@forrestmid真的很感激你如何實現'file.createWriteStream'直接上傳的例子。謝謝! – Nag