[英]How to upload files on changing the select menu options using multer in nodejs?
[英]How upload files and optimize them before upload using multer - NodeJs
我正在使用 Nodejs、react 和 mongo 做一個社交網絡。 我正在使用 multer 上傳圖像,但我需要在上傳到目錄之前對其進行優化。
穆爾特
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, "./uploads/publications");
},
filename(req, file = {}, cb) {
const { originalname } = file;
const fileExtension = (originalname.match(/\.+[\S]+$/) || [])[0];
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString("hex") + Date.now() + fileExtension);
});
},
});
var mul_upload = multer({ dest: "./uploads/publications", storage });
路線
app.post(
"/publication",
[md_auth.ensureAuth, mul_upload.single("image")],
PublicationController.savePublication
);
是否可以在上傳之前壓縮和優化圖像?
您需要使用 npm package。 鋒利的它可能是一個非常好的選擇。
const sharp = require('sharp')
sharp(req.file).resize(200, 200).toBuffer(function(err, buf) {
if (err) return next(err)
// you can do anything with the buffer
})
使用multer
,您可以實現自定義存儲 function。 你可以在這里查看如何操作。 我在這里添加示例代碼:
var fs = require('fs')
function getDestination(req, file, cb) {
cb(null, '/dev/null')
}
function MyCustomStorage(opts) {
this.getDestination = (opts.destination || getDestination)
}
MyCustomStorage.prototype._handleFile = function _handleFile(req, file, cb) {
this.getDestination(req, file, function(err, path) {
if (err) return cb(err)
var outStream = fs.createWriteStream(path)
var resizer = sharp().resize(200, 200).png()
file.stream.pipe(resizer).pipe(outStream)
outStream.on('error', cb)
outStream.on('finish', function() {
cb(null, {
path: path,
size: outStream.bytesWritten
})
})
})
}
MyCustomStorage.prototype._removeFile = function _removeFile(req, file, cb) {
fs.unlink(file.path, cb)
}
module.exports = function(opts) {
return new MyCustomStorage(opts)
}
對於 reactJs 這里是 npm package
npm i react-image-file-resizer
對於 NodeJ
npm i react-image-file-resizer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.