如何使用输入类型文件附加我选择的文件?
<form action="/upload" method="POST" enctype="multipart/form-data" >
<div class="file-field input-field">
<div class="btn grey">
<span>File</span>
<input name="myImage" type="file" multiple="multiple">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
这是后端代码
var mailOptions = {
from: '****@gmail.com',
to: '*****@gmail.com',
subject: 'test',
text: 'test',
attachments: [{
// how to get the path of the selected file
}]
};
我怎样才能获得包含在附件中的路径?
附件params是文件路径,因此我认为您必须先将上传的文件写入磁盘,然后再将其附加到邮件中。您可以使用nodejs fs模块来执行此操作。
const fs = require('fs').promises
...
fs.writeFile('/your/path/to/your/fs', fileContent)
.then(res => {
const mailOptions = {
from: '****@gmail.com',
to: '*****@gmail.com',
subject: 'test',
text: 'test',
attachments: ['/path/to/your/fs']
};
// I suppose sendMail return a Promise here !
return sendMail(mailOptions)
}).then(_ => fs.unlink('path/to/your/fs'))
// fs.unlink is here to delete the file because it is useless now
使用此代码从请求对象中提取文件数组,然后将此文件数组作为附件传递给nodemailer
var files = req.files;
const mailOptions = {
from: '****@gmail.com',
to: '*****@gmail.com',
subject: 'test',
text: 'test',
attachments: files
};