Search code examples
javascriptimagefile-uploadcanvasnode.js

In Node.js how to convert a multipart/form-data uploaded image to base64 format


I want to allow a user to select an image from their local filesystem and then render this image to a canvas element on the page.

Due to the security constraints ('sandbox' browser security model), the client javascript cannot directly access the image on the filesystem, so it has to do a round trip to the server as 'multipart/form-data' from a file upload control.

I don't want to actually save this image on the server and serve it out, since it's only for one-time client-side manipulation purposes. So, I was wondering if is possible to convert the image data server-side into a base64 encoded representation which could be sent back to the client. Then I could easily draw it back to the client as a data URL without ever saving the image anywhere on the server. Or is there a better way?

I am using node.js on the server.


Solution

  • I don't see a need to save it on the server or incur the cost of Base64 encoding a data URI; just store it in memory long enough for the client to download. So your sequence will go something like this:

    1. The client uploads the image via a "multipart/form-data" submission.
    2. As the server receives the form it generates a "throw-away" URL (which could be, e.g., returned as the response body to the request in #1); the image file data is simply stored in memory.
    3. The client may retrieve the image data from the URL in #2.
    4. When the client requests the URL in #2 the server simply echoes the image data; upon completion of the request the server may drop the data reference, thus freeing the memory.

    Note that due to the asynchronous nature of both node.js and AJAX requests items 1-4 could be done concurrently (although the "throw-away" URL might have to be agreed upon separately from the form post for it to really work that way).