简体   繁体   中英

How to create image file on server using dataURL?

In my app I have used canvas on which the user can draw images. On save button I get the dataURL from the canvas. Now I want to save the image created by user on the server(node.js). I have read Node file system documentation but I am not sure what I can/should use! Also up till now I have only used forms for posting data to server and now I need to post the data on the click of save button, what should I do?

So there are two parts to the answer,

Client behavior and server behavior. There's a lot of raw information missing here.

First we assume you have a mechanism of getting the raw stream for the content in the format it needs to be when you convert it to an image "file" or binary content in a datastore (or xml for svg, etc.) If you have that raw stream content you're going to use a standard XmlHttpRequest to post the content to a url. On the node.js process you need a route and a function that is going to "catch" the streamed content and persist it in your storage mechanism (file, db as blob, export to an external service, etc.)

So when you ask how on the client side, it's by posting to a url using XmlHttpRequest (dojo.xhr, jQuery.ajax, etc.) stream the raw content out as the "body" of the post programatically. Bind a function to a dom element's onClick method that takes the image content and posts it to the server url.

jQuery('#postDiv').click(function() {
    jQuery.ajax({
       type : 'POST',
       url : '/myapp/image/<id>',
       data : someComponentInMyPage.getImageContent(),
       success : function() { // show the user it worked },
       datatype : 'image/png' // or whatever format is coming out
    });
 });

On the server, take the input stream and write it to a file, this is going to depend on the frameworks/modules you're using on the node side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM