Readme

getBlobAndRenderAsImage

Shows how to get a Val Town blob and render it as an image in the DOM with React.

Setup

Make sure you have an image named test.png in your Val Town blob storage (alternatively, you can change the key name in the blob getter in the script).

To easily upload an image to your blob storage, fork this val, run it, and enter your API key in the password input.

How it works

  1. Fetching the blob:
  • The client-side React component makes a fetch request to "/image".
  • This request is handled by our server function.
  1. Server-side handling:
  • The server function calls blob.get("test.png").
  • This blob.get() method makes an HTTP request to the Val Town API.
  • The API returns a Response object containing the image data.
  1. Processing the blob on the server:
  • We receive this Response object from blob.get().
  • We don't need to extract the data on the server side.
  • We can directly return this Response object to the client.
  1. Sending the response to the client:
  • We set the appropriate "Content-Type" header (e.g., "image/png").
  • We return the Response object to the client.
  1. Client-side handling:
  • The fetch request in the React component receives the Response.
  • We call response.blob() to get a Blob object from the Response.
  1. Creating a data URL:
  • We create a FileReader object.
  • We use FileReader to read the Blob as a data URL.
  • This data URL is a base64-encoded string representing the image.
  1. Updating the React state:
  • We set the data URL as the state of our component.
  1. Rendering the image:
  • We use the data URL as the src attribute of an <img> tag.
  • The browser decodes the base64 data and renders the image.

Further reading on Val Town blobs

Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
ashryanio-getblobandrenderasimage.web.val.run
October 1, 2024