【发布时间】:2022-11-21 18:53:13
【问题描述】:
我正在编写有关将图像上传到谷歌云的功能的代码。我可以将图片上传到 gcloud 但无法在上传前调整它的大小。我尝试使用 node js sharp library 来调整大小但无法正确实现它。下面是我的代码:
我的上传功能
const processFile = require('../middleware/upload')
const { format } = require('util')
const { Storage } = require('@google-cloud/storage')
// Instantiate a storage client with credentials
const storage = new Storage({ keyFilename: 'xxxxx.json' })
const bucket = storage.bucket('<---bucket name--->')
const upload = async (req, res) => {
try {
await processFile(req, res)
if (!req.file) {
return res.status(400).send({ message: 'Please upload a file!' })
}
// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(req.file.originalname.replace(/ /g, "_"))
const blobStream = blob.createWriteStream({
resumable: false,
})
blobStream.on('error', (err) => {
res.status(500).send({ message: err.message })
})
blobStream.on('finish', async (data) => {
// Create URL for directly file access via HTTP.
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`,
)
try {
// Make the file public
await bucket.file(req.file.originalname).makePublic()
} catch {
return res.status(500).send({
message: `Uploaded the file successfully: ${req.file.originalname}, but public access is denied!`,
url: publicUrl,
})
}
res.status(200).send({
message: 'Uploaded the file successfully: ' + req.file.originalname,
url: publicUrl,
})
})
blobStream.end(req.file.buffer)
} catch (err) {
if (err.code == "LIMIT_FILE_SIZE") {
return res.status(500).send({
message: "File size cannot be larger than 2MB!",
});
}
res.status(500).send({
message: `Could not upload the file: ${req.file.originalname}. ${err}`,
})
}
}
module.exports = {
upload
}
我的 Multer 库
const processFile = require('../middleware/upload')
const util = require("util");
const Multer = require("multer");
const maxSize = 2 * 1024 * 1024;
let processFile = Multer({
storage: Multer.memoryStorage(),
limits: { fileSize: maxSize },
}).single("file");
let processFileMiddleware = util.promisify(processFile);
module.exports = processFileMiddleware;
上面的代码能够将图像推送到 gcloud。有人可以建议如何使用 node js sharp 调整它的大小并上传到 gcloud。先感谢您
【问题讨论】:
-
这回答了你的问题了吗? Node.js: image resizing without ImageMagick
标签: javascript node.js google-api-nodejs-client sharp