代码之家  ›  专栏  ›  技术社区  ›  swigganicks

从google云功能上传图片到云存储

  •  3
  • swigganicks  · 技术社区  · 7 年前

    我正在尝试使用google云功能处理文件上传。此函数使用busboy解析多部分表单数据,然后上载到google云存储。

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

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

    请注意,我无法生成中建议的签名上载URL this question 因为调用它的应用程序是一个外部的非用户应用程序。我也不能直接上传到gcs,因为我需要根据一些请求元数据创建自定义文件名。我应该改用谷歌应用引擎吗?

    功能代码:

    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 回复  |  直到 7 年前
        1
  •  1
  •   swigganicks    7 年前

    我最终放弃了使用勤杂工。最新版本的google云函数同时支持python和node 8。在node 8中,我只是将所有内容放入async/await函数中,它工作得很好。