1

I am trying to send post request to backend containing base64url encoded value of my image. When I send request with any random string, the request is received at backend but when I try to do same thing using encoded value, it responds me back with

request failed with status code 500

My code for the request is:

const uploadFileHandler = async (e) => {
  const file = e.target.files[0];

  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onloadend = () => {
    setPreviewSource(reader.result);

    uploadtobackend(reader.result);
  };
  const uploadtobackend = async (filedata) => {
    try {
      const config = {
        headers: {
          'Content-Type': 'application/json',
        },
      };
      console.log(config);
      console.log(filedata);

      const { data } = await axios.post(
        `/api/uploads`,
        {
          data: filedata,
        },
        config,
      );
      setImages(data);
      setUploading(false);
    } catch (error) {
      console.log(error);
      setUploading(false);
    }
  };
};

Here filedata is the encoded value and it is displayed if I console it. Instead of

data: filedata

If I send

data: "some random string"

then request reaches backend otherwise not.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • I think you need use `multipart/form-data` with `FormData`. Checkout [this](https://stackoverflow.com/a/47630754/6516699) – Naren Dec 11 '20 at 15:36

2 Answers2

1

You nedd to send your file by wrapping in FormData. You can do something like

const fd = new FormData()
// data you want to send other than file
fd.append('payload',JSON.stringify(payload))

fd.append('file',file) // file you want to send to node backend

Now in your backed you can get this file using req.file

folan
  • 215
  • 1
  • 8
1

Probably you need to use JSON.stringify() here are some example of use

const { data } = await axios.post(
    `/api/uploads`,
    {
       data: new Buffer(JSON.stringify(filedata)).toString("base64")
    },
    config
 )