更新 到目前为止我尝试了什么
app.post('/jobs/join-us', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
// `file` is the name of the <input> field of type `file`
var old_path = files.file.path,
file_size = files.file.size,
file_ext = files.file.name.split('.').pop(),
index = old_path.lastIndexOf('/') + 1,
file_name = old_path.substr(index),
new_path = path.join(process.env.PWD, '/uploads/', file_name + '.' + file_ext);
fs.readFile(old_path, function(err, data) {
fs.writeFile(new_path, data, function(err) {
fs.unlink(old_path, function(err) {
if (err) {
res.status(500);
res.json({'success': false});
} else {
res.status(200);
res.json({'success': true});
}
});
});
});
});
我有一个联系表格,人们可以申请工作,这需要将简历上传到我的网站。 如何使用nodemailer和multer发送附件? 我发送电子邮件的app.js:
app.post('/jobs/join-us', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
const output = `
<p>You have a new message from contact form.</p>
<h3>Contact Details</h3>
<ul>
<li>Role: ${req.body.role}</li>
<li>First name: ${req.body.first_name}</li>
<li>Last name: ${req.body.last_name}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
<li>Agreement: ${req.body.agreement}</li>
<li>Referer: ${req.body.referer}</li>
<li>CV: ${req.files}</li>
</ul>
<h3>Message</h3>
<p>${req.body.description}</p>
`;
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'xx', // generated ethereal user
pass: 'xx',
},
tls: {
rejectUnauthorized: false
}
});
我还尝试在app.post下添加console.log(req.files),但它似乎没有返回任何内容,有人可以提供给我指导吗?
答案 0 :(得分:0)
你必须告诉multer哪个字段名称负责处理文件上传,请看下面的例子:
HTML:
<form action="/jobs/join-us" method="post">
<input name="role" type="text">
...
<input type="file" name="cv">
</form>
快递:
app.post('/jobs/join-us', upload.single('cv'), function (req, res, next) {
...
});
注意:如果您只想上传一个文件,那么最好使用single()
,array()
方法可以处理多个文件上传
NodeMailer:
您创建了传输器对象,但是您忘记使用它来发送包含附件中上传文件的电子邮件:
transporter.sendMail({
from: 'foo@example.com', // sender
to: 'bar@example.com', // receiver
subject: 'Contact Details', // Subject
html: output, // message body
attachments: [
{
filename: req.file.originalname,
path: req.file.path
}
]
}, (error, info) => {
if (error) {
return console.log(error);
}
})