1

My code isn't working as it should, it keeps receiving a 400 from the server and failing to upload. I must be making mistakes in the react component so please can you take a look for me? All's working in Postman, so the backend code seems fine.

import React, { useState } from "react";
import axios from "axios";

const UploadAvatar = () => {
  const [image, setImage] = useState();

  const handleUpload = async (e) => {
    e.preventDefault();
    const config = {
      headers: {
        "content-type": "multipart/form-data",
        Authorization: localStorage.getItem("token"),
      },
    };
    try {
      const formData = new FormData();
      formData.append("avatar", image);
      const response = await axios.post(
        "/users/me/avatar",
        { formData },
        config
      );
      console.log(response);
    } catch (err) {
      console.error(err.message);
    }
  };

  return (
    <div>
      <form onSubmit={handleUpload}>
        Select image to upload:
        <input
          type="file"
          onChange={(e) => setImage(e.target.value)}
          name="fileToUpload"
        />
        <input type="submit" value="Upload Image" name="submit" />
      </form>
    </div>
  );
};

export default UploadAvatar;
8
  • What is the error message you are getting? And also check the curl if it's matching with that of postman. Commented Aug 19, 2020 at 21:45
  • 400 bad request, yes it's matching :) Commented Aug 19, 2020 at 21:52
  • if curl is matching, i dont think there is any issue in the code. you are posting file, try changing onChange function to onChange={(e) => setImage(e.target.files[0])}. Commented Aug 19, 2020 at 22:30
  • Thanks Nitesh, but I still get a 400 :/ Commented Aug 19, 2020 at 22:57
  • Did you set base URL properly? Commented Aug 20, 2020 at 6:46

2 Answers 2

2
+50

There some things you need to do.

This is not related to the problem, but I think it is worth checking:

const config = {
      headers: {
        "content-type": "multipart/form-data",
        Authorization: localStorage.getItem("token"),
      },
    }
  1. What scheme is your Authorization (Basic, Bearer, OAuth)?

    . If its a Bearer schema (e.g.), is your localStorage.getItem("token") returning only the token or is returning "Bearer {token}"? For bearer token, you need to include the word 'Bearer' before the token.

  2. The content-type it's not really necessary here, but you can let it there if you prefer.

In your code, you need to do some changes:

In your handleUpload you need to do this:

try {
      const formData = new FormData();
      formData.append("avatar", image);
      // I just removed the curly brackets from formData
      const response = await api.post("/users/me/avatar", formData, config);
      console.log(response);
} catch (err) {
      console.error(err.message);
}

And in your input file type:

<input
          type="file"
          onChange={(e) => setImage(e.target.files[0])}
          name="fileToUpload"
/>

For input file types, the target should be e.target.files, wich returns a list of files and each file is a FileList object. As you sending only one image you can set it as e.target.files[0] to get the first image.

And that´s all. It should work now! :) I did a poc here and everything goes ok.

Sign up to request clarification or add additional context in comments.

Comments

1

for bad request

it happens because of axios , your not sending json data

in your code

const response = await axios.post(
        "/users/me/avatar",
        { formData },<---------here is the problem object
         formData  ,<-------try without curly brazes or use below detailed axios 
        config
      );
      console.log(response);
    } catch (err) {
      console.error(err.message);
    }
  };

change axios

axios({
    method: 'post',
    url: 'myurl',
    data: formData ,
    headers: {'Content-Type': 'multipart/form-data' }
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });

another problem

YOUR SENDING FILES

 <input
          type="file"
          onChange={(e) => setImage(e.target.value)}<-------wrong e.target.files[0]
          name="fileToUpload"
        />

change if u sending mutliple files

e.target.files

or if you sending single file use

e.target.files[0]

change code

 <input  type="file"
          onChange={(e) => setImage(e.target.files[0])}
          name="fileToUpload"
        />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.