I could make Contact Form by using Gatsby Functions and SendGrid. The value of Input text and Textarea can be successfully sent, but I am wondering how I can handle the file to upload and send. <input type="file" id="formFile" />
In the case of Next.js' API Router, it seems to be possible by installing "Next-connect" and "multiparty" package.
Any idea in the case of Gatsby Functions?
api/form_sent.js
export default function formHandler(req, res) {
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_APIKEY);
const { method, body } = req;
const mailData = {
from: process.env.AUTHORIZED_SENDER,
to: body.formEmail,
subject: 'question from web',
html: `<p>${body.formName}<p>${body.formTextarea}</p>`,
}
const results = sgMail.send(mailData)
.then(result => res.status(200).json(JSON.stringify(result)))
.catch(error => res.status(500).json(JSON.stringify(error)))
}
pages/form.js
import * as React from "react"
import Layout from "../components/layout"
export default function FormPage() {
const [serverResponse, setServerResponse] = React.useState(``)
async function onSubmit(e) {
e.preventDefault()
const response = await window
.fetch(`/api/send`, {
method: `POST`,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(value),
})
.then(res => res.json())
setServerResponse(response)
}
return (
<Layout>
<form onSubmit={onSubmit} method="POST" action="/api/send">
<input type="text" id="formName" />
<input type="email" id="formEmail" />
<textarea id="formTextarea"></textarea>
<input type="file" id="formFile" />
<button type="submit">Send</button>
</form>
</Layout>