【问题标题】:Upload image from local directory to Google Cloud Storage using Node JS使用 Node JS 将图像从本地目录上传到 Google Cloud Storage
【发布时间】:2021-01-16 13:32:03
【问题描述】:

我正在使用 Node JS / Express,想从 url 下载文件到本地系统,然后在下一步将其上传到 Google Cloud Storage。

这是我的带有中间件的路由器:

  router.post("", fileFromUrl, uploadFromUrl, scrapeController.scrapeCreateOne);

这是一个 fileFromUrl 中间件,它只是将文件从 url 保存到本地磁盘

module.exports = (req, res, next) => {
try {
    console.log('Image: ', req.body.image);

    const url = req.body.image ? req.body.image : '';
    console.log(typeof url);

    if(url === '') {
        //no image url provided
        console.log('image parsing skipped');
        next()
    }
    else {
         // image url ok then 
        const pathToImage = path.resolve(__dirname, '..', 'images', Date.now() + '_file.jpg');
        const localPath = fs.createWriteStream(pathToImage);
        
        const saveFile = https.get(url, (response) => {
            console.log(response.headers['content-type']);
            response.pipe(localPath);
        })

        req.body.customImageUrl = pathToImage;
        req.body.customImageName = path.basename(pathToImage);
        
        next();
    }

}
catch (error) {
    console.log(error)
}

}

这是 uploadFromUrl 中间件,应该将文件从本地路径上传到 Google 云存储

module.exports = (req, res, next) => {
try {
    console.log(req.body.customImageUrl);
    console.log(req.body.customImageName);
    //storage.getBuckets().then(x => console.log(x));
    //storage.createBucket(`testbucket_${Date.now()}`); / // it does work
    storage.bucket(bucketName).upload(req.body.customImageUrl, {
        gzip: true,
        metadata: {
        cacheControl: 'public, max-age=31536000',
        },
    }).then(
        req.body.customData = `https://storage.googleapis.com/${bucketName}/${req.body.customImageName}`
    ); 
    next();
}
catch (error) {
    res.send(error).json({
        message: 'Error upload middleware' + error,
    });
}

}

现在所做的只是将 20kB 的几乎空文件上传到 Google Cloud Platform,而不是完整图像。我觉得我没有为 uploadFromUrl 中间件提供适当的文件对象。另一方面,上传文件的 GCP API 只是询问正在提供的文件的路径。有什么想法吗?

【问题讨论】:

  • 嗨@luk 你确认当你在本地保存文件时它的大小正确吗?这应该可以确认下载文件或上传文件时是否存在问题。
  • 嗨@gso_gabriel 是的,第一个中间件(fileFromUrl)正确地将图像保存在我节点服务器上的图像文件夹中。我可以查看所有文件,它们的大小确实合适
  • 嗨@luk,如果它正在保存,可能与您传递给上传的URL有关。考虑到这一点,您能否按照本教程here 尝试一下,看看它是否对您有帮助?它提供了一些关于如何将本地文件上传到 GCS 的示例。
  • 再次感谢您。我还没有找到解决方案,但我发现了问题。如果我将请求分解为两个,并调用一个请求将文件从 url 保存到本地服务器磁盘,然后第二个请求获取这个保存的文件并上传到 GCP,这一切都和预期的一样好。一定是我尝试将尚未完全保存在本地服务器上的文件上传到 GCP 的问题
  • 很高兴您找到了解决问题的方法。但是,实际的答案/解决方案应该被编辑到您的问题中。一般来说,您应该edit 问题来澄清它,但不要在其中包含答案。您应该使用用于解决问题的代码/解决方案创建自己的答案,然后接受它(系统可能需要 48 小时延迟才能这样做)。当您自己解决问题后,answering your own question is encouraged

标签: node.js google-cloud-platform


【解决方案1】:

问题是我试图将图像上传到 GCP,即使图像尚未完全保存在服务器上。解决方案是在我发出的请求中等待“完成”事件以将其保存在本地

 const pathToImage = path.resolve(__dirname, '..', 'images', Date.now() + '_file.jpg');
        const localPath = fs.createWriteStream(pathToImage);
        const fileRelativePath = "images/" + path.basename(pathToImage);
        const request = https.get(url, (response) => {
            //console.log(response.headers['content-type']);
            response.pipe(localPath).on('finish', () => {
                console.log('image saved on the server');
                req.body.customImagePath = fileRelativePath;
                req.body.customImageName = path.basename(pathToImage);
                // now you can go and upload the image to GCP in the next moddleware
                next();
            });
        });

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2017-08-11
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多