简体   繁体   English

NodeJS:-如何使用multer在mongo DB中存储表单中的图像并将相同的图像作为附件发送到邮件

[英]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 :最好的方法是:

  1. upload image to your server directory or some file hosting site.将图像上传到您的服务器目录或某些文件托管站点。
  2. get url of image from your local server or file hosting server.从本地服务器或文件托管服务器获取图像的 url。
  3. saved that address in your database.将该地址保存在您的数据库中。
  4. use that address as image src.使用该地址作为图像 src。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Multer Storage Cloudinary 从同一表单上传音频和图像 - Upload audio and image from the same form using Multer Storage Cloudinary 使用 Multer 提交表单时如何防止图像保存 - How to Prevent an Image from Saving When Submitting Form Using Multer 如何仅使用socket.io和multer使用套接字发送图像以保存在我的NodeJS后端中 - How can I send an image using sockets to save in my NodeJS backend using just socket.io and multer 如何使用multer和express在数据库中发送图像名称 - how to send image name in database using multer and express 如何使用 google-api-nodejs-client for nodejs 在 gmail api 中发送带有附件的邮件 - How to send a mail with an attachment in gmail api using google-api-nodejs-client for nodejs 当我从 PostMan 发送图像文件时,NodeJS multer 出现错误(req.file 未定义) - When I send image file from PostMan, NodeJS multer has an error (req.file is undefined) Mongo / Mongoose / Multer / FS删除图像 - Mongo/Mongoose/Multer/FS to delete an image 如何使用 multer、Nodejs、JS 存储上传的文件? - How to store uploaded files using multer , Nodejs , JS? 如何使用JAVA在MONGO DB中存储值? - How to store values in MONGO DB using JAVA? 如何使用mailto和使用JavaScript和html从Outlook中的附件自动发送邮件 - how to send mail automatically using mailto with attachment from outlook using JavaScript and html
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM