0

How do I send an image to my node js server with axios in react without a form? I'm using nodemailer on server side to send an email with text and an image attachment. The code below is what I have and it does not work as I'm not actually sending the file itself. The code works fine for sending text.

import img from "./image.jpg";

const handleRequest = async () => {
  const body = {
    img,
  };
  await axios
    .post("http://localhost:3030/mail", body)
    .then((res) => {
      console.log("Email Sent Successfully");
  })
  .catch((err) => {
    console.log(err);
  });
};
magikarp
  • 21
  • 4
  • Depends what Content-Type your API is designed to accept. But you could use a Blob and encode it in JSON data. Or you can create programatically a FormData and innsert your Blob in it. In any I think case you'lll have to encapsulate your image in a blob. – Peterrabbit Mar 10 '22 at 12:26
  • Okay but how do encapsulate my image in a blob? – magikarp Mar 10 '22 at 14:24
  • You can have a look at this https://stackoverflow.com/questions/42471755/convert-image-into-blob-using-javascript this https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob and this sould help too https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects – Peterrabbit Mar 10 '22 at 15:02

0 Answers0