[英]NodeJS:-How to store image from a form in mongo DB using multer and send the same image to mail as an attachment
I was implementing a website where the user inputs details.我正在实施一个用户输入详细信息的网站。 There is also an option for the user to attach images/pdf (less than 5MB) in the form.
用户还可以选择在表单中附加图像/pdf(小于 5MB)。 I wanted to store the entire image in my MongoDB as well as send the image to my mail account using node nodemailer.
我想将整个图像存储在我的 MongoDB 中,并使用 node nodemailer 将图像发送到我的邮件帐户。
Everything else is working that is I am able to send the mail with the details inputted by the user, but can't save image in my database or send it to a mail account.其他一切正常,即我能够发送包含用户输入的详细信息的邮件,但无法将图像保存在我的数据库中或将其发送到邮件帐户。
The below is the code I have implemented下面是我已经实现的代码
server.js:- server.js:-
const express = require("express");
const multer = require('multer');
const path = require('path');
const app = express ();
app.set("view engine", "ejs");
const mongoose= require("mongoose");
const router = express.Router();
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const User=require("./models/User");
// Multer image start
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './public/uploads/');
},
filename: function(req, file, cb) {
cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname); //replace is used to save in computer readable format
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
}
});
mongoose.connect("mongodb://localhost/emergen");
var bodyParser = require('body-parser');
//Middleware
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var uploadFile = upload.single('image');
app.post('/send', uploadFile, (req, res) => {
var name = req.body.name;
var email = req.body.email;
var phone = req.body.phone;
var message = req.body.message;
var image = req.file.originalname;
var newUser= {name:name,email:email,phone:phone,message:message,image:image};
User.create(newUser,function(err,newCreatedUser){
if(err){
console.log(err);
}
else{
console.log(newCreatedUser);
}
})
// Mailer implementation
var output = `
<p>You have a new Contact Request from Emergen Website</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
<li>Phone: ${req.file.path}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
// <h3>Attachment</h3> Attachments if need to be added above in output
// <p>${req.body.attachment}</p>
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'JackRogers@gmail.com',
pass: '******'
}, tls:{
rejectUnauthorized:false // remove when uploading on server
}
}));
var mailOptions = {
from: 'qwerty@gmail.com',
to: 'asd@gmail.com',
subject: 'New Enquiry for Emergen',
text: 'That was easy!',
html: output
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
res.redirect('/contact-us');
});
});
My model, User.js:-我的模型,User.js:-
const mongoose=require("mongoose");
const UserSchema= new mongoose.Schema({
name:String,
email:String,
phone:Number,
message:String,
image: { data: Buffer, contentType: String }
});
module.exports= mongoose.model("User",UserSchema);
my form, contact-us.ejs:-我的表格,contact-us.ejs:-
<form class="text-center border border-light p-5" method="POST" action="send" enctype="multipart/form-data">
<p class="h4 mb-4">Contact us</p>
<!-- Name -->
<input type="text" id="FormName" class="form-control mb-4" placeholder="Name" name="name" required>
<!-- Email -->
<input type="email" id="FormEmail" class="form-control mb-4" placeholder="E-mail" name="email" required>
<input type="text" id="FormContact" class="form-control mb-4" placeholder="Contact No" name="phone" required>
<!-- Message -->
<div class="form-group">
<textarea class="form-control rounded-0" id="exampleFormControlTextarea2" rows="5" placeholder="Message" name="message" required></textarea>
</div>
<!-- Attachment -->
<div class="form-group">
<label for="name">Document Upload:</label>
<input type="file" class="form-control" id="image" name="image" >
</div>
<!-- Send button -->
<button class="btn btn-info btn-block" type="submit">Send</button>
</form>
Please help me.Stuck on it for a while now请帮帮我。现在坚持了一段时间
Saving image in database is considered very bad practice.在数据库中保存图像被认为是非常糟糕的做法。
Preferable way is to :最好的方法是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.