skip to Main Content

db.json
The image file I posted to my db.json is missing.

const createPost = async (title, image, description) => {
 const data = new FormData();
    data.append('title', title);
    data.append('image', image);
    data.append('description', description);

    const response = await axios.post('http://localhost:3001/posts', data, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    const updatedPosts = [...posts, response.data];
    setPosts(updatedPosts);
  };
export const Form = ({ createPost }) => {
  const [image, setImage] = useState(null);

  const submitForm = (e) => {
    e.preventDefault();

    createPost(title, image, description);
    setImage('');
    setTitle('');
    setDescription('');
  };

  const uploadImage = (e) => {
    const file = e.target.files[0];
    setImage(file);
  };

  return (
    <form onSubmit={submitForm} encType="multipart/form-data">
      <div className="image">
        <label>Import Image</label>
        <input type="file" accept="image/*" onChange={(e) => uploadImage(e)} />
      </div>
      <div className="action">
        <Button className="button">Create</Button>
      </div>
    </form>
  );
};

I want to post my data to my server. But, only an image file is missing in my db.json. What is the better way I fixed the code?

3

Answers


  1. I think your header’s content type have to be multipart/form-data or you have to convert your image to base64 string and no need to add it to form data and also if you are using express you may have to use bodyparserand fs packages too.

    Login or Signup to reply.
  2. onChange takes only function name. So, modify this

    onChange={(e) => uploadImage(e)}
    

    to

    onChange={uploadImage}
    

    because you have already defined uploadImage function earlier in your code.

    Login or Signup to reply.
  3. I don’t know, but I think your problem is in the Backend code. But, try to Change the order of data.append, move data.append(file) to the last.

    data.append('title', title)
    data.append('description', description)
    // ...appends some field
    data.append('file', file)
    

    If not work, please show me your backend code. (how to generate db.json file)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search