如何从客户端使用nodejs中的mongoose在mongodb中调整和添加图像,并能够在ejs中查看图像



我想调整图像的大小并将其上传到Mongo DB。是否可以在节点中完成并用猫鼬表达,请添加代码解释。这将对非常有帮助

最终完成了multer、gridfs和jimp(主包)

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const crypto = require("crypto")
const Jimp = require("jimp")
const app = express();
// Middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
app.use(express.static("public"));
// Mongo URI
const mongoURI = 'mongodb://localhost:27017/newDB';
// Create mongo connection
//useUnifiedTopology will not work with mongoose.createConnection
const conn = mongoose.createConnection(mongoURI , { useUnifiedTopology: true ,useNewUrlParser: true });
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
mongoose.connect("mongodb://localhost:27017/newDB", { useUnifiedTopology: true, useNewUrlParser: true })
const imageSchema = new mongoose.Schema({
image: String,
User: String,
forTest: String
});
const Image = mongoose.model('image', imageSchema);

// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
app.get('/', (req, res) => {
Image.find({}, function(err, files)  {
// Check if files
if (!files || files.length === 0) {
res.render('index', { fileSent: false });
} else {
res.render('index', { fileSent: files });
}
});
});
app.post('/upload', upload.single("file"), (req, res) => {
if(req.file === undefined || req.file === 0 || req.file === ""){
res.redirect("/");
}
if(req.file.contentType === "image/png" || req.file.contentType === "image/jpg" || req.file.contentType === "image/jpeg"){
Jimp.read("http://localhost:3000/image/" + req.file.filename, (err, image) => {
if (err) {
// on every error render the error page with error message and type
console.log(err);
}
image
.resize(550, Jimp.AUTO)
image.getBase64(Jimp.AUTO, (error1, base64Image) => {
if(error1){
console.log(error1);
}
const image1 = new Image({
image: base64Image,
User: "Avichal",
forTest: "Hindi1"
})
image1.save(function(error){
if(error){
console.log(error);
}
})
})
gfs.remove({ _id: req.file.id, root: 'uploads' }, (err, gridStore) => {
if (err) {
console.log(err);
}
res.redirect('/');
});
})
}else{
gfs.remove({ _id: req.file.id, root: 'uploads' }, (err, gridStore) => {
if (err) {
console.log(err);
}
res.redirect('/');
});
}
});
app.get('/:filename', (req, res) => {
Image.findOne({ image: req.params.filename }, (err, file) => {
// Check if the input is a valid image or not
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// If the file exists then it is an image
// Read output to browser
const readstream = Image.createReadStream(file.image);
readstream.pipe(res);
});
});
//for reading the multer image(it is important as first read the multer image with jimp read and then resize it and then delete the multer image)
app.get('/:image/:filename', (req, res) => {
if(req.params.image === "image"){
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if the input is a valid image or not
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// If the file exists then check whether it is an image
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
}
});
app.delete('/files/:id', (req, res) => {
Image.deleteOne({_id: req.params.id}, function (err) {
if (err) {
console.log(err);
}
});
res.redirect("/")
});
app.listen(3000, () => console.log("Server started on port 3000"));

最新更新