【问题标题】:Upload Image from Google Cloud Function to Cloud Storage将图片从 Google Cloud Function 上传到 Cloud Storage
【发布时间】:2018-07-12 03:47:28
【问题描述】:

我正在尝试使用 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 回调函数中。

请注意,我无法按照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();
    }
}

【问题讨论】:

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


    【解决方案1】:

    我最终放弃了使用 Busboy。最新版本的 Google Cloud Functions 支持 Python 和 Node 8。在节点 8 中,我只是将所有内容放入 async/await 函数中,它工作正常。

    【讨论】:

    • 你好@swigganicks 如果你解决了我也面临同样的问题,你能否详细解释或发布一些示例代码。提前致谢。
    • @swigganicks,如果样品朝向相同,将不胜感激
    • 对不起,我没有它的代码了。我最终改用 Python。
    猜你喜欢
    • 2018-07-04
    • 2021-04-25
    • 2020-04-08
    • 2019-02-14
    • 2017-08-11
    • 2015-02-21
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    相关资源
    最近更新 更多