Upload image file and data to API from form in Next js


Hey guys,
I am in need of help with a personal project.
I have an API made with STRAPI and I made a form on my page to “feed” this API, as follows Schema below:

{
  "id": "string",
  "nome": "string",
  "slug": "Unknown Type: uid",
  "email": "string",
  "mensagem": "string",
  "picture": {
    "id": "string",
    "name": "string",
    "alternativeText": "string",
    "caption": "string",
    "width": 0,
    "height": 0,
    "formats": {},
    "hash": "string",
    "ext": "string",
    "mime": "string",
    "size": 0,
    "url": "string",
    "previewUrl": "string",
    "provider": "string",
    "provider_metadata": {},
    "related": "string",
    "created_by": "string",
    "updated_by": "string"
  }
}

And the code of the form that is working but only for string (name, email and mensage):
COD:

import { useState } from "react";

export default function FormDepoimentos() {
  const [depoimentoNome, setDepoimentoNome] = useState("");
  const [depoimentoEmail, setDepoimentoEmail] = useState("");
  const [depoimentoMensagem, setDepoimentoMensagem] = useState("");

  async function addDepoimento() {
    const depoimentoInfo = {
      nome: depoimentoNome,
      slug: depoimentoNome.toLowerCase().replace(/\s/g, ""),
      email: depoimentoEmail,
      mensagem: depoimentoMensagem,
    };

    const add = await fetch("https://joanita-api.herokuapp.com/depoimentos", {
      method: "POST",
      headers: {
        Accept: "apllication/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(depoimentoInfo),
    });
    const addResponse = await add.json();

    console.log(addResponse);
  }

  return (
    <>
      <form className="w-full space-y-2 md:space-y-4">
        <div className="flex items-center justify-between pl-3 border border-gray-200 rounded-lg shadow-sm overflow-hidden">
          <input
            type="text"
            onChange={(e) => setDepoimentoNome(e.target.value)}
            value={depoimentoNome}
            name="nome"
            className="text-sm font-light outline-none h-12 w-11/12 text-red-800 placeholder-red-800"
            placeholder="Nome"
          />
        </div>

        <div className="flex items-center justify-between pl-3 border border-gray-200 rounded-lg shadow-sm overflow-hidden">
          <input
            type="email"
            onChange={(e) => setDepoimentoEmail(e.target.value)}
            value={depoimentoEmail}
            name="email"
            className="text-sm font-light outline-none h-12 w-11/12 text-red-800 placeholder-red-800"
            placeholder="E-mail"
          />
        </div>

        <div className="flex items-center justify-between pl-3 border border-gray-200 rounded-lg shadow-sm overflow-hidden">
          <textarea
            onChange={(e) => setDepoimentoMensagem(e.target.value)}
            value={depoimentoMensagem}
            name="mensage"
            className="text-sm font-light outline-none h-24 w-full py-2 text-red-800 placeholder-red-800"
            placeholder="Mensagem"
          />
        </div>

<div className=' pl-3 text-red-800 text-sm'>Enviar Foto</div>
              <div className="flex  pl-3 pt-3 pb-0 border border-gray-200 rounded-lg shadow-sm overflow-hidden">
                <input
                  type="file"
                  name="file"
                  className="text-sm font-light outline-none h-12 w-11/12 text-red-800 placeholder-red-800"
                />
              </div>

        <div className="bg-red-800 rounded-lg py-2">
          <button
            className="w-full text-base font-Nunito text-white tracking-wider hover:font-bold hover:text-xl"
            type="button"
            onClick={() => addDepoimento()}
          >
            Enviar
          </button>
        </div>
      </form>
    </>
  );
}```

**How do I upload an image too?**
<img width="1338" alt="Screenshot 2021-05-11 at 08 39 02" src="https://user-images.githubusercontent.com/69011104/117881950-bb7de180-b2a1-11eb-98e6-ca86f284770e.png">

If you want to upload files during entry creation, it is a little bit different.

I’ve created a Codesandbox to show you how it works:

First of all, I would like to thank you for your attention and apologize for taking the time to return.
However I can’t do what I wanted, I think I need to study a little more to be able to use your code, but I really appreciate your help.

1 Like

Hey @sunnyson,
I’m trying to make similar example work with cloudinary, but in response image is always null.
Have to mention that creating entry at first and then uploading an image works as charm. Is it possible to upload form data with image file (and having it proccessed with cloudinary) and then to get all data with cloudinaries images in response?

Actually solved it by completely removing Content-Type header from fetch, though multipart/form-data didn’t work

1 Like