Multer req.file返回未定义

时间:2020-10-09 16:21:49

标签: javascript html node.js sendgrid multer

我正在尝试使用multer上传文件。其他所有数据都在发布,但在文件输入方面却变得不确定。我正在尝试使用sendGrid API将附件发送到邮件。

Html

<form id="form" enctype="multipart/form-data">
  <div>
    <div class="input-field">
      <input id="email" type="email" required />
      <label class="active" for="email">To </label>
    </div>

    <div class="file-field input-field">
      <div class="btn btn-small">
        <span><i class="small material-icons">attach_file</i></span>
        <input type="file" id="fileInput" name="fileInput" />
      </div>
      <div class="file-path-wrapper">
        <input class="file-path" type="text" placeholder="attach a file?">
      </div>
    </div>

    <div class="input-field">
      <input id="subject" type="text" required />
      <label class="active" for="subject">Subject</label>
    </div>

    <div class="input-field hide">
      <input id="content" type="text" />
      <label class="active" for="content"></label>
    </div>
  </div>

  

  <div class="w-md">
    <div id="toolbar"></div>
    <div id="editor"></div>
  </div>

  <div class="mt-2 mb-2 center">
    <button class="btn waves-effect waves-light btn-small" id="btn" type="submit">Submit
      <i class="small material-icons right">send</i>
    </button>
  </div>
</form>



index.js

    const sendMail = () => {
      const email = getIds('email').value;
      const subject = getIds('subject').value;
      const myBtn = getIds('btn');
      const htmlFormat = quill.root.innerHTML;
      const content = (getIds('content').value = htmlFormat);
      const data = {
        email,
        subject,
        content,
      };
      // const formData = new FormData();
      // formData.append('data', data);
    
      console.log(data);
      myBtn.disabled = true;
      axios
        .post('/send', data, {
          headers: {
            'Content-Type': 'application/json',
          },
        })
        .then((res) => {
          myBtn.disabled = false;
          form.reset();
          quill.setContents([{ insert: '\n' }]);
          M.toast({ html: 'Email Sent!', classes: '' });
          console.log(res);
        })
        .catch((err) => {
          myBtn.disabled = false;
          M.toast({ html: `Error: ${err.message}` });
          console.log(err);
        });
    };
    
    form.addEventListener('submit', (e) => {
      e.preventDefault();
      sendMail();
    });

我不知道我在这里实际上是否在做错什么,这就是为什么我评论formData的原因。

app.js(nodejs后端)

...
const multer = require('multer');
// const upload = multer({ dest: './uploads/' });
const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './uploads/');
  },
  filename: (req, file, cb) => {
    cb(
      null,
      `${file.fieldname}-${Date.now()}-${path.extname(file.originalname)}`
    );
  },
});

const upload = multer({ storage: multerStorage });

app.post('/send', upload.single('fileInput'), async (req, res) => {
  const sendMail = () => {
    return new Promise(async (resolve, reject) => {
      // pathToAttachment = `${__dirname}/attachment.pdf`;
      // attachment = fs.readFileSync(pathToAttachment).toString('base64');
      const file = req.file;
      const { email, content, subject } = req.body;
      console.log(file);
      // returns undefined
      console.log(req.body);
      const filePath = fs.createReadStream(file.path);

      pathToAttachment = `${filePath}`;
      attachment = fs.readFileSync(pathToAttachment).toString('base64');
      if (!file) {
        return res.json({
          message: 'Select a file',
        });
      } else {
        try {
          setApiKey();
          const msg = {
            to: [`${email}`],
            from: 'test123@gmail.com', // Use the email address or domain you verified above
            subject: `${subject}`,
            html: `${content}`,
            attachments: [
              {
                content: attachment,
                filename: file[0].originalname,
                type: file.mimetype,
                disposition: 'attachment',
              },
            ],
          };
          const result = await sgMail.send(msg);
          resolve(result);
          console.log('Message sent!');
        } catch (err) {
          console.log('Error in sendEmail: ', err.response.body);
          reject(err.response.body);
        }
      }
    });
  };
  try {
    await sendMail();
    res.json({
      message: 'Message Sent!',
    });
  } catch (error) {
    res.status(400).json({
      message: 'Something went wrong',
    });
  }
});

// Setting PORT from config
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started on ${PORT}`));

我知道这个问题已经问了很多遍了,我实际上不知道我在哪里做错了。

2 个答案:

答案 0 :(得分:0)

请尝试此步骤解决问题

  1. 删除请求方法上的标题

axios.post('/send', data)

  1. 取消注释表单数据部分
const formData = new FormData();
formData.append('data', data);
    multer中间件上的
  1. 必须与数据名称匹配

upload.single('data') // instead of "fileInput"

答案 1 :(得分:0)

我认为这对其他人很有用,我通过删除用于获取表单的前端代码来解决此问题:

index.js

const sendMail = () => {
  const email = getIds('email').value;
  const subject = getIds('subject').value;
  const myBtn = getIds('btn');
  const htmlFormat = quill.root.innerHTML;
  const content = (getIds('content').value = htmlFormat);
  const data = {
    email,
    subject,
    content,
  };
  // const formData = new FormData();
  // formData.append('data', data);

  console.log(data);
  myBtn.disabled = true;
  axios
    .post('/send', data, {
      headers: {
        'Content-Type': 'application/json',
      },
    })
    .then((res) => {
      myBtn.disabled = false;
      form.reset();
      quill.setContents([{ insert: '\n' }]);
      M.toast({ html: 'Email Sent!', classes: '' });
      console.log(res);
    })
    .catch((err) => {
      myBtn.disabled = false;
      M.toast({ html: `Error: ${err.message}` });
      console.log(err);
    });
};

form.addEventListener('submit', (e) => {
  e.preventDefault();
  sendMail();
});

并通过以下操作让Multer包完成工作 req.file ,该文件现已可用,并且我还确保我在所有文件上都具有 name属性输入

我也删除了这一行

const filePath = fs.createReadStream(file.path);