0

In my frontend I'm using input[type='file'] to get image data from the users, and POST to my API. In the backend, I'm parsing the data using formidable. The issue is that uploadImage Api returns input buffer contains unsupported image format.

Note** -> I can upload the file to sanity cdn directly from the frontend, but it expose my token in the browser, and sanity don't prefer it.

frontend->

export default function Component() {
  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const file = e.currentTarget[0]?.files[0];
    const formdata = new FormData();
    formdata.append("file", file);

    fetch("/api/uploadImage", {
      method: "POST",
      body: formdata,
    })
      .then((res) => res.json())
      .then((r) => console.log(r))
      .catch((err) => console.log(err));
  };

  return (
    <div>
      <form encType="multipart/form-data" onSubmit={handleSubmit}>
        <input type="file" id="inputFile" name="avatar" />
        <button
          type="submit"
          className="rounded-md bg-indigo-500 px-4 py-1 text-white"
        >
          Select some files
        </button>
      </form>
    </div>
  );
}

backend->

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const data = await new Promise((resolve, reject) => {
    const form = formidable();
    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
      }
      resolve({ req, fields, files });
    });
  });
  const { fields, files } = data;

  try {
    const { _id } = await client.assets.upload("image", files);
    res.status(200).json(_id);
  } catch (err) {
    res.status(400).send(err);
  }
}
1
  • What is files, an array? Does client.assets.upload work with an array of files?
    – James
    Mar 18 at 22:41

1 Answer 1

0

The FormData constructor already encodes files propertly. You can simplify your component immensely -

function FileUpload() {
  const handleSubmit = (event) => {
    event.preventDefault()
    fetch("/api/upload", {
      method: "POST",
      body: new FormData(event.target),
    })
    .then((response) => { … })
    .catch((error) => { … });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="file"
        name="myfile"
        accept=".jpg, .jpeg, .png"
      />
      <button>Upload</button>
    </form>
  )
}

Or try this demo that displays the uploaded image directly in the browser -

function App() {
  const [img, setImg] = React.useState(null)
  const handleSubmit = (event) => {
    event.preventDefault()
    const formData = new FormData(event.target)
    const reader = new FileReader()
    reader.onload = (event) => {
      setImg(event.target.result)
    }
    reader.readAsDataURL(formData.get("myfile"))
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="file"
        name="myfile"
        accept=".jpg, .jpeg, .png"
      />
      <button>Upload</button>
      {img && <img src={img} />}
    </form>
  );
}

ReactDOM.createRoot(document.querySelector("#app")).render(<App />)
img { max-width: 100vw; }
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

The backend route would look something like this -

async function uploadImage(req, res) {
  if (req.method !== "POST") {
    return res.status(405).end() // Method Not Allowed
  }

  const form = new IncomingForm({ multiples: false })

  form.parse(req, async (err, fields, files) => {
    if (err) {
      console.error(err)
      return res.status(500).end() // Internal Server Error
    }

    const { myfile } = files

    if (!myfile) {
      return res.status(400).end() // Bad Request
    }

    try {
      const result = await client.asset.upload("image", myfile, { filename: myfile.name })
      console.log("uploaded image:", result.asset._id)
      return res.status(200).json({ fileId: result.asset._id })
    } catch (error) {
      console.error(error)
      return res.status(500).end() // Internal Server Error
    }
  })
}
9
  • i don't want to display the image on the browser. I'm trying to upload the image to sanity cdn using the uploadImage API
    – Amit Kumar
    Mar 18 at 21:39
  • ... i can't demonstrate uploading the image in the browser. that is included for additional background on how to work with file uploads to demonstrate proper functionality. follow the first code example for making a POST request.
    – Mulan
    Mar 18 at 21:40
  • I can make successful post request to the uploadImage API, but when trying to upload the image using client.asset.upload() it returns the following error mentioned in the title. But the things is that if I use client.asset.upload(file) [here file is the variable] in the frontend, i can upload the image to sanity cdn. But I want to upload the image through uploadImage api
    – Amit Kumar
    Mar 18 at 21:46
  • i'm struggling at `try { const { _id } = await client.assets.upload("image", files); res.status(200).json(_id); } catch (err) { res.status(400).send(err); }
    – Amit Kumar
    Mar 18 at 21:57
  • i can't the upload parsed image data to sanity cdn.
    – Amit Kumar
    Mar 18 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.