如何使用multer node js将图片上传到谷歌云



如果存储是memoryStorage,我已经在NodeJS中使用Multer完成了上传,因为文件首先保存在缓冲区中,然后从缓冲区我可以上传到Google Drive,

但如果使用内存存储,我不能重命名图像文件,

我使用multer.diskStorage,但当我发布时,文件成功上传但没有上传图片,文件大小变小了,比如10B。

这是我在助手中的代码,函数为uploadImage

const util = require('util')
const gc = require('../config/')
const bucket = gc.bucket('jsimage')//bucket name
const { format } = util
const uploadImage = (file) => new Promise((resolve, reject) => {
console.log(file);
//const { originalname, buffer } = file
const { filename, destination } = file
//const blob = bucket.file(originalname.replace(/ /g, "_"))
const blob = bucket.file(filename)
const blobStream = blob.createWriteStream({
resumable: false
})
blobStream.on('finish', () => {
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`
)
resolve(publicUrl)
})
.on('error', () => {
reject(`Unable to upload image, something went wrong`)
})
//.end(buffer)
.end(destination)
})
module.exports = uploadImage

使用上面的代码,我成功地上传到了谷歌硬盘,但没有上传图片,因为大小总是10B。

在这个例子中,图片上传到temp或任何本地文件夹后,我们可以将其上传到谷歌云。

const util = require('util')
const gc = require('../config/')
const bucket = gc.bucket('jsimage')//bucket name di google drive
const path = require('path')
const { format } = util
// promises are built right away, so there's no need for then to resolve and catch for errors
const uploadImage = (file) => new Promise((resolve, reject) => {
//console.log(file);
const {filename} = file;
const picture = path.join(__dirname,'../uploads/',filename);
// This is the upload command
bucket.upload(picture);
// This is sent to return
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${filename}`
)
resolve(publicUrl)
reject(err=>(err))
})
module.exports = uploadImage

最新更新