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 re开发者_如何学Pythonnder 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.
go to https://github.com/joyent/node/wiki/modules, grab a base64 encoding library and simply echo out data:image/png;base64,
followed by the base-64 encoded file, replacing "png" with whatever is appropriate (gif/jpeg)
the "better" way is to actually drop the file into a tmp folder, echo a link to that file and then delete all files in that directory that are older than X minutes.
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:
- The client uploads the image via a "multipart/form-data" submission.
- 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.
- The client may retrieve the image data from the URL in #2.
- 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).
精彩评论