How can I send a File to my Strapi app using Fetch API in the Front-End?

Viewed 573

I'm trying to Upload a File to Strapi using Fetch API in the front-end to make this request.


async function sendForm(e) {
  e.preventDefault();
  // URL
  let url = '/upload';

  // Headers
  const headers = new Headers();
  // headers.append('Authorization', 'YOUR AUTH METHOD HERE');
  headers.append('Content-Type', 'multipart/form-data');

  // Form Data
  const data = new FormData();
  data.append('files', file.files[0]);
  console.log(data.get('files')) // Shows File

  const req = await fetch(url ,
    {
      method: 'POST',
      headers,
      data
    }
  );

  const res = await req.json();
  console.log(res); // Shows File Empty Error
}

This results in the Error response:

data: {…}
​​
errors: (1) […]
​​​
0: Object { id: "Upload.status.empty", message: "Files are empty" }
​​​
length: 1
​​​
<prototype>: Array []
​​
<prototype>: Object { … }
​
error: "Bad Request"
​
message: "Bad Request"
​
statusCode: 400

I don't understand why this happens.

If you want to recreate this exact scenario I've uploaded my files to Github, just copy and paste these files to the /public folder.
https://github.com/mitri-dev/strapi-app-issue

Thanks for your time.

0 Answers
Related