Search code examples
node.jsreactjsfile-uploadmulter

File upload in React and Node.js


I want to upload an image from the React.js but it is not working.

basically it is not updating the image field and remains the same like following: enter image description here

It should update the path of /images/samples.jpeg but after I upload the file it remains the same and does not change

The fileUploadHandler:

const uploadFileHandler = async (e) => {
    const file = e.target.files[0];
    let formData = new FormData();
    formData.append("image", file);
    setUploading(true);

    try {
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      const { data } = await axios.post(
        "http://localhost:5000/api/upload",
        formData,
        config
      );
      setImage(data);
      setUploading(false);
    } catch (error) {
      setUploading(false);
    }
  };

If I log the formData in the try block then it does not logs anything so is the data field and logs the error as below: enter image description here

<Form.Group controlId="image">
  <Form.Label>Image</Form.Label>
  <Form.Control
    type="text"
    placeholder="Upload Image url"
    value={image}
    onChange={(e) => setImage(e.target.value)}
  ></Form.Control>
  <Form.Control
    type="file"
    label="Choose file"
    onChange={uploadFileHandler}
  ></Form.Control>
  {uploading && <Loader />}
</Form.Group>

Everything is fine in the backend but still getting the error.


Solution

  • File input submiting section

      onSubmit = async (values) => {
        const { postRequest,  } = this.props
       
        const uploadFileEle = document.getElementById("fileInput")
        let file = uploadFileEle.files[0];
        let formData = new FormData();
    
        formData.set('file', file);
    
        postRequest('image', formData)
       
      }
     <input className="photo-upload" id="fileInput" type="file" onChange={(this.onSubmit)} />
    

    axios post section

     export const postRequest = (namespace, values, { url = undefined, notification = undefined }={}) => async (dispatch, getState) => {
         
        try {
            dispatch(request(namespace));
            const res = await post(`http://localhost:3000/${namespace}`, values);
        
            if (res.data.errorCode) {
              dispatch(res.data.errorCode, 'error');
            } else {
              dispatch(success(namespace, res.data.result));
           
               dispatch( 'success');
            }
          } catch (error) {
            dispatch(failure(namespace, error));
            if (error.response !== undefined) {
              dispatch(error.response.status, 'error');
            } else {
              dispatch('500', 'error');
            }
            throw error;
          }
        }