0

I am trying to upload a file using Axios and send it to a strapi local server. This is how I am sending the data with Axios

const Form = () => {
  
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append("selectedFile", selectedFile[0]);
    try {
      const response = await axios({
        method: "post",
        url: "http://localhost:1337/document-uploads",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      });
    } catch (error) {
      console.log(error);
    }
  };

  const handleFileSelect = (event) => {
    setSelectedFile(event.target.files[0]);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileSelect} />
      <input type="submit" value="Upload File" />
    </form>
  );
};

export default Form;

The message that I am getting is: error 400 and "when using multipart/form-data you need to provide your data in a json 'data' field"

  • I think you want `formData.append("selectedFile", selectedFile)` (without the `[0]` since you've already extracted the first file in the array in your `handleFileSelect` function. You also [should not set the content-type header](https://stackoverflow.com/a/68643919/283366) – Phil Nov 22 '21 at 23:02
  • What you're doing doesn't look like the [Strapi uploads examples](https://strapi.io/documentation/developer-docs/latest/development/plugins/upload.html) at all. Why are you naming the field `selectedFile`? What guide are you following? – Phil Nov 22 '21 at 23:04
  • Thank you Phil, I had to change the code after read the documentation carefully. – Nelson Rosales Nov 23 '21 at 19:21

0 Answers0