Tuesday, March 15, 2016

Using the Signature Pad jQuery Plugin with SharePoint & InfoPath – Redux

I’m using Thomas Bradley’s Signature Pad plugin for a project, which I’ve used successfully before. The twist this time is that I want to save the signature as an image rather than just as JSON.

There’s a method called getSignatureImage()  that works just fine to grab the signature as a base64 string, like so (this is the result for an empty canvas):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArwAAACWCAYAAAA8Els6AAAIjElEQ…QIECBg8LoBAgQIECBAgACBtIDBm65XOAIECBAgQIAAgQtmc1xdE+aNPAAAAABJRU5ErkJggg==

(Note the “…”; it’s a much longer string.)

Snazzy signatureI was having a problem saving the signature to a library successfully. Uploading the file was easy, but the image file was always ending up corrupted. It didn’t matter if I uploaded to a Document library or Picture Library; no joy.

I knew I was missing something obvious. I tried removing the leading “data:image/png;base64,”. I tried different values for Content-Type, etc. It had to be something about the way I was creating the file.

In the end, I got some great advice from a colleague. The base64 content has to be *decoded* so that we can save it. This is what worked:

// Get the base64-encoded image from the plugin
var img = signatureArea.getSignatureImage();
var outfile = fakefilename(); // I'm creating a unique filename to use for saving in my testing

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl +
        "/_api/web/getfolderbyserverrelativeurl('/path/to/my/picture/library/')/files/add(overwrite=true, url='" + outfile + "')",
    type: "POST",
    data: convertDataURIToBinary(img),
    processData: false,
    headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function() {
        $("#sig-file").attr("src", outfile); // Show the image file in the form
    }
});

// Useful function "borrowed" from http://ift.tt/1R0JrMc
// Decodes the base64 text data back into the binary data representation of the image file
var convertDataURIToBinary = function(dataURI) {
    var base64Marker = ";base64,";
    var base64Index = dataURI.indexOf(base64Marker) + base64Marker.length;
    var base64 = dataURI.substring(base64Index);
    var raw = window.atob(base64);
    var rawLength = raw.length;
    var array = new window.Uint8Array(new window.ArrayBuffer(rawLength));

    for (i = 0; i < rawLength; i++) {
        array[i] = raw.charCodeAt(i);
    }
    return array;
};

by Marc D Anderson via Marc D Anderson's Blog

No comments:

Post a Comment