簡體   English   中英

將圖像從Google Cloud功能上傳到雲端存儲

[英]Upload Image from Google Cloud Function to Cloud Storage

我正在嘗試使用Google Cloud功能處理文件上傳。 此功能使用Busboy解析多部分表單數據,然后上傳到Google Cloud Storage。

我一直收到同樣的錯誤: ERROR: { Error: ENOENT: no such file or directory, open '/tmp/xxx.png'在觸發函數時ERROR: { Error: ENOENT: no such file or directory, open '/tmp/xxx.png'錯誤。

當storage.bucket.upload(file)嘗試打開文件路徑/tmp/xxx.png時,錯誤似乎發生在finish回調函數中。

請注意,由於調用此應用程序的應用程序是外部非用戶應用程序,因此無法生成此問題中建議的已簽名上載URL。 我也無法直接上傳到GCS,因為我需要根據一些請求元數據制作自定義文件名。 我應該只使用Google App Engine嗎?

功能碼:

const path = require('path');
const os = require('os');
const fs = require('fs');
const Busboy = require('busboy');
const Storage = require('@google-cloud/storage');
const _ = require('lodash');

const projectId = 'xxx';
const bucketName = 'xxx';


const storage = new Storage({
  projectId: projectId,
});

exports.uploadFile = (req, res) => {
    if (req.method === 'POST') {
        const busboy = new Busboy({ headers: req.headers });
        const uploads = []
        const tmpdir = os.tmpdir();

        busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
            const filepath = path.join(tmpdir, filename)
            var obj = {
                path: filepath, 
                name: filename
            }
            uploads.push(obj);

            var writeStream = fs.createWriteStream(obj.path);
            file.pipe(writeStream);
        });

        busboy.on('finish', () => {
            _.forEach(uploads, function(file) {

                storage
                .bucket(bucketName)
                .upload(file.path, {name: file.name})
                .then(() => {
                  console.log(`${file.name} uploaded to ${bucketName}.`);
                })
                .catch(err => {
                  console.error('ERROR:', err);
                });


                fs.unlinkSync(file.path);
            })

            res.end()
        });

        busboy.end(req.rawBody);
    } else {
        res.status(405).end();
    }
}

我最終放棄了使用Busboy。 最新版本的Google Cloud Functions支持Python和Node 8.在節點8中,我只是將所有內容放入async / await函數中,它運行正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM