Unable to create image file using createObjectURL after upgrade to NextJS 13 from 10

511 views Asked by At

I have a website that does the following:

  1. On the client side, call an api endpoint passing just the URL of an image from the internet
  2. On the server side, get the image by URL and return the image data as an arrayBuffer
  3. On the client side then extract the arrayBuffer data and create a Blob object from it
  4. Finally save that Blob as a file

The current website works with the following details:

NextJS: 10.2.3 React: 17.0.2 Node: 14.x Webpack: 5

However after upgrading to the below details it fails to create the image file

NextJS: 13.4.19 React: 18.2.0 Node: 18.x Webpack: 5

Code:

// pages/api/getImageData.js

import axios from "axios";

export default async (req, res) => {

    const url = new URL(req.body);

    // console.log(url)

    const imageData = await axios.get(url.toString(),{
        responseType: 'arraybuffer',
    });

    res.status(200).json(imageData.data);

}
// pages/index.js

await fetch("/api/getImageData", {
        method: "POST",
        body: fileSrc
      })
      .then(res => res.json())
      .then(json => json.data)
      .then(bufferData => new Blob([bufferData], {type: "image/*"}))
      .then(blob => {
        console.log(blob)
        try{
          var url = URL.createObjectURL(blob)
          console.log("Image created: " + url)
          // return url
        }
        catch(e)
        {
          console.log(e)
        }

// result of logging the blob
//
// Blob {size: 1673339, type: "image/*", slice: function, stream: function, text: function, …}
//

I'm able to get the Blob object (with content) however on the next line where I call URL.createObjectURL(blob) the file does not actually get created and the url returned does not resolve (just returns nextjs 404 error "This page could not be found")

enter image description here

enter image description here

Ive tried on Chrome and Safari with no luck

Can someone please tell me what im doing wrong, thanks

Ive tried testing on different browsers and adding logging while debugging to see the flow of data however its still not clear to me why its failing

I expected the file to load

1

There are 1 answers

0
daviddev95 On

Found my issue after seeing JS - displaying blob image result to a broken image icon

Needed to convert the response data array to a Uint8Array

      .then(res => res.json())
      .then(json => json.data)
      .then(bufferData => new Uint8Array(bufferData))
      .then(uint8Array => new Blob([uint8Array]))
      .then(blob => URL.createObjectURL(blob))
      .then(url => img.src = url)
      .catch(err => console.error(err));