HTML and CSS Reference
In-Depth Information
url: '/SaveInSQLServer.aspx/SaveToDb',
data: '{ "data" : "' + data + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image data saved to SQL Server database!');
As shown here, the click event handler of a button triggers the save operation. Inside the click event
handler, toDataURL() is called and the Base64-encoded data is stored in a local variable. You need to send
only the image data to the server; hence the beginning of the string ( 'data:image/png;base64,' ) is
removed using the JavaScript replace() function. Of course, if you wish to render the images in image
elements using the data URL technique discussed earlier, you need not remove the beginning of the string.
The $.ajax() method then makes a POST request to a web method named SaveToDb() . The Base64-
encoded image data is passed to the server as a JSON object. The SaveToDb() web method is shown in
Listing 4-22.
Listing 4-22. SaveToDb() Web Method
public static void SaveToDb(string data)
ImageDbEntities db = new ImageDbEntities();
Image img = new Image();
img.ImageData = data;
img.SaveDate = DateTime.Now;
The SaveToDb() method receives the Base64-encoded image data as a parameter. Inside, it uses an
Entity Framework data model class ( Image ) to save the data in a SQL Server table named Images . If you run
this example and check the ImageDb database from the App_Data folder, you find that a record is added to
the Images table every time you click the Save button.
Saving the Canvas Drawing as an Image File on the Server
At times, saving a canvas drawing as a physical disk file on the server is more convenient than storing the
image in a database. For example, consider a case where you wish to send the canvas drawing as an e-mail
attachment. In such a case, attaching a canvas drawing saved as a physical image file is more convenient
and simplifies your task.
Saving a canvas drawing as a server-side image is similar to the previous technique. This time,
however, you need to convert the Base64-encoded data back to its binary representation and then save it
as a disk file. Converting Base64-encoded data to its binary form is necessary because you save it in a
physical image file rather than a SQL Server database. The jQuery code remains almost identical to the
previous example, but the web method needs some modifications. Listing 4-23 shows the $.ajax() call
being made to a web method named SaveAsImageFile .
Search WWH ::

Custom Search