3

I am trying to pass a blob with the type of "image/jpeg" from nodeJS to react. In the nodejs end, I pass the data using arraybuffer and on the react end, I try to retrieve it using res.blob which should usually convert the data back. The thing is axios is returning an error saying res.blob() is not a function. How do I retrieve it in the react end then? Any response will be most appreciated and I apologize if I haven't described my issue well enough.

This is my code in nodejs

  res.type(blob.type);
  blob.arrayBuffer().then((buf) => {
    res.end(Buffer.from(buf));
  });

And this is my code in react.

    axios
    .post(imageUrl)
    .then((res) => {
      return res.blob();
    })
    .then((blob) => {
      storageRef
        .child(path + filename)
        .put(blob)
        .then(function (snapshot) {
          return snapshot.ref.getDownloadURL();
        })
Raja Shilan
  • 43
  • 1
  • 7
  • Use `res.arrayBuffer()` instead of `res.blob()`. – Hassan Imam Aug 16 '21 at 16:50
  • 3
    Set `responseType: 'blob'` to axios options, then get response by `res.data`. check [this](https://stackoverflow.com/questions/60454048/how-does-axios-handle-blob-vs-arraybuffer-as-responsetype) answer – Amin Taghikhani Aug 16 '21 at 16:57
  • @HassanImam I tried using res.arrayBuffer() but I get an error saying res.arrayBuffer() is not a function, similar to res.blob() – Raja Shilan Aug 16 '21 at 17:27
  • @AminTaghikhani I just tried your suggestion, but in firebase storage, the image is uploaded as an "octet-stream/application" filetype, and the size of the uploaded file is 9bytes as opposed to the original 130+kb size. – Raja Shilan Aug 16 '21 at 17:28
  • Why are you not storing the blob on the server where it's at and returning the download url? – Oluwafemi Sule Aug 16 '21 at 17:49
  • @OluwafemiSule I could, but I'm using Firebase's cloud storage service and its sdk allows for a much easier upload on the client side. – Raja Shilan Aug 17 '21 at 03:55
  • Did you find a solution for this. I am having the same problem. – Buwaneka Sudheera Aug 20 '21 at 07:10
  • @BuwanekaSudheera No I couldn't find a good solution. Instead, I ditched axios and decided to use fetch just for that particular api. Fetch works with res.blob without any problems. – Raja Shilan Aug 21 '21 at 09:10

1 Answers1

6

When using axios you don't need to use blob(), just set responseType: 'blob' to axios options. e.g.

axios.get(PF + userCreds.user.profilePic, {responseType: 'blob'})

and after that in the .then() function instead of

.then(axios.spread((...responses) => {
    responses.map((res) => (
        console.log(URL.createObjectURL(res.data.blob())
    ))
}))

do that

.then(axios.spread((...responses) => {
    responses.map((res) => (
        console.log(URL.createObjectURL(res.data))
    ))
}))

the result is the same as fetch

KemerDev-C
  • 71
  • 1
  • 6