关于javascript:将图片从Google Cloud Function上载到Cloud Storage

Upload Image from Google Cloud Function to Cloud Storage

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

我一直收到相同的错误:触发功能时出现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吗?

功能代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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和Node8。在node 8中,我将所有内容都放入了async / await函数中,并且运行良好。