如何使用 multer 和 NodeJS 将图像上传到 GCS 存储桶? [英] How to upload images to GCS bucket with multer and NodeJS?

查看:27
本文介绍了如何使用 multer 和 NodeJS 将图像上传到 GCS 存储桶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将本地图片上传到我的谷歌云存储时遇到了问题.

I'm facing issues for uploading local images to my google cloud storage.

我已经尝试了两种方法.第一个是用multer上传

I've already tried two methods. The first one is uploading with multer

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, './uploads/')
    },
    filename: (req, file, cb) => {
      cb(null, file.fieldname + '-' + Date.now())
    }
});
var upload = multer({storage: storage}).single('image'); 

app.post('/upload',function(req,res,next){
  upload(req,res,(err) => {
    if(err){
      console.log(err)
    }else{
      console.log(req.file)
    }
  })

})

然后,我直接用 GCS 试过了

Then, i've tried directly with GCS

var bucket = admin.storage().bucket('mybucket')
app.post('/upload',function(req,res,next){
 bucket
.save(file)
.then(() => {



})

对于这两种解决方案,req.files 总是 undefinedreq.body 是这样的缓冲区:

for both of these solutions , req.files is always undefined whereas req.body is a buffer like this :

<缓冲区 2d 2d 2d 2d ...>

当我尝试将此缓冲区保存在我的 GCS 存储桶中时,我的存储桶中创建了 .jpg/png 文件,但它已损坏.

when i try to save this buffer on my GCS bucket, i the .jpg/png file is created in my bucket but it is corrupted.

我正在浏览网页寻找解决方案,但没有发现任何可以帮助我克服这种情况的方法.

I'm browsing the web seeking for a solution but i found nothing that helped me to overcome this situation.

有什么建议吗?

推荐答案

如果你有额外的表单值,你需要 multer、multer-google-storage 和当然 bodyParser.您需要在 multipart/form-data 中发送数据

You need multer, multer-google-storage and ofcourse bodyParser if you have additional form values. You need to sent data in multipart/form-data

在你的 .env 文件中

In your .env file

GCS_BUCKET = <bucket name>
GCLOUD_PROJECT = <project id>
GCS_KEYFILE = <key file location>

您可以从 GCP Console>Your Project>I AM & 下载密钥文件管理员>服务帐户

You can download key file from GCP Console>Your Project>I AM & Admin>Service Accounts

在你的路线中

const multer = require('multer');
const multerGoogleStorage = require("multer-google-storage");

var uploadHandler = multer({
  storage: multerGoogleStorage.storageEngine()
});

router.post('/', uploadHandler.single('image'), function (req, res, next) {
  const body = req.body;
  res.json({fileName: req.file.filename});
  res.end();

}

这会将文件存储到 GCS,名称为 [random-string-generated-by-gcs]_[YOUR FILE NAME WITH EXTENTION].同样可以通过req.file.filename在路由下访问.

This will store file on to GCS with name [random-string-generated-by-gcs]_[YOUR FILE NAME WITH EXTENTION]. The same can be access under the route via req.file.filename.

文档

这篇关于如何使用 multer 和 NodeJS 将图像上传到 GCS 存储桶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆