js для создания контактной формы, которая отправит администратору сайта электронное письмо с данными формы и вложением в формате PDF.
Я devtool console.log, я могу распечатать файл объекта, но в бэкенте я получаю файл загрузки в виде файла: {'0': {}}.
Вот мой код. Внешний интерфейс: Реагирующий компонент:
const { file } = data
const uploadFile = file[0]
console.log("uploadFile", uploadFile)
const res = await sendContactMail(data, uploadFile, formType, recipientMail)
}
...
return(
<form onSubmit={handleSubmit(SubmitForm)}>
<div className="flex justify-between">
<div className="w-1/2">
<span>📎</span>Attach File
<input
type="file"
name="file"
className="border-"
ref={register({ required: true })}
/>
</div>
{/* </input> */}
<Button type="submit" title="SEND" className="py-2 px-6" />
</div>
</form>
)
mail-api: (пожалуйста, игнорируйте поле ввода, отличное от файла)
import axios from "axios"
interface MailerPros {
firstName: string
lastName: string
emailAddress: string
phoneNumber: string
interest: string
message: string
uploadFile: any
recipientMail: string
}
export const sendContactMail = async (
contactData: MailerPros,
uploadFile: any,
formType: string,
recipientMail: string
) => {
const formData = {
...contactData,
uploadFile,
formType,
recipientMail,
}
console.log("uploadFile3", uploadFile)
// use the formData to post the file to the server
// const formData = new FormData()
// formData.append("uploadFile", uploadFile)
// formData.append("formType", formType)
// formData.append("recipientMail", recipientMail)
try {
const res = await axios({
method: "post",
url: "/api/contact",
headers: {
// "Content-Type": "multipart/form-data; boundary=${form._boundary}",
"Content-Type": "application/json",
},
data: formData,
})
return res
} catch (error) {
return error
}
}
Код бэкенда:
import nodemailer from "nodemailer"
const transporter = nodemailer.createTransport({
service: "Gmail",
port: 465,
// need to be provided from env
auth: {
user: process.env.CONTACT_EMAIL_USER,
pass: process.env.CONTACT_EMAIL_PSWD,
},
})
interface MailerPros {
firstName: string
lastName: string
emailAddress: string
phoneNumber: string
interest: string
message: string
recipientMail: string
formType: string
uploadFile: any
}
const mailer = ({
firstName,
lastName,
emailAddress,
phoneNumber,
interest,
message: content,
formType,
recipientMail,
uploadFile,
}: MailerPros) => {
console.log("uploadFile2", uploadFile)
const name = firstName + lastName
const from =
name && emailAddress
? `${name} <${emailAddress}>`
: `${name || emailAddress}`
const mailOptions = {
from,
to: `${recipientMail}`,
subject: `New message from ${from} (Metrix Website)`,
content,
replyTo: from,
html: `
<h3>Dear ${recipientMail},</h3>
<p>${firstName} ${lastName} (${emailAddress} has send you a <b>${formType}</b> request. His/her contact number is <b>${phoneNumber}</b>. He/she is interested in <b>${interest}</b>.
<br/>Here is his/her meesage:</p>
<p>"${content}"</p>
`,
attachments: [
{
filename: uploadFile.name + ".pdf",
contentType: uploadFile.type,
},
],
}
return new Promise((resolve, reject) => {
transporter.sendMail(mailOptions, (error, info) => {
error ? reject(error) : resolve(info)
transporter.close()
})
})
}
export default async (req: any, res: any) => {
console.log("req", req)
const {
firstName,
lastName,
emailAddress,
phoneNumber,
interest,
message: content,
recipientMail,
formType,
uploadFile,
} = req.body
// console.log("uploadFile1", uploadFile)
// Check if fields are all filled
if (req.body === "") {
res.status(403).send("")
return
}
const mailerRes = await mailer({
firstName,
lastName,
emailAddress,
phoneNumber,
interest,
message: content,
uploadFile,
formType,
recipientMail,
})
// console.log("mailerRes", mailerRes)
res.send(mailerRes)
}