将图像从Google Cloud Function上传到Cloud Storage

时间:2018-07-12 03:47:28

标签: javascript node.js google-cloud-storage google-cloud-functions busboy

我正在尝试使用Google Cloud Function处理文件上传。此功能使用Busboy解析多部分表单数据,然后上传到Google Cloud Storage。

我一直收到相同的错误:触发该功能时发生ERROR: { Error: ENOENT: no such file or directory, open '/tmp/xxx.png'错误。

当storage.bucket.upload(file)尝试打开文件路径finish时,在/tmp/xxx.png回调函数中似乎发生了错误。

请注意,由于调用该应用程序是外部非用户应用程序,因此无法按照this question中的建议生成签名的上传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();
    }
}

1 个答案:

答案 0 :(得分:1)

我最终放弃了使用Busboy。最新版本的Google Cloud Functions支持Python和Node8。在Node 8中,我将所有内容都放入了async / await函数中,并且运行良好。