如何使用multer和NodeJS将图像上传到GCS存储桶? [英] How to upload images to GCS bucket with multer and NodeJS?
问题描述
我在将本地图像上传到我的Google云存储时遇到问题.
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
总是 undefined
,而 req.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.
我正在浏览Web寻求解决方案,但没有发现任何可以帮助我克服这种情况的方法.
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文件中
GCS_BUCKET = <bucket name>
GCLOUD_PROJECT = <project id>
GCS_KEYFILE = <key file location>
您可以从GCP控制台>您的项目> I AM&Admin>服务帐户
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();
}
这会将文件存储到名称为[random-string-generated-by-gcs] _ [您的文件名带有扩展名]的GCS上.可以通过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屋!