Question

I have a list with 2 columns namely DistributorLogo and BaseURL as shown below.

The Distributor logo column contains an image URL

enter image description here

I am trying to get the image URL from the DistributorLogo column and save the resultant base64 value to the BaseURL Column

Code to get all the list items:

function GetItemId()
  {
    //debugger;
    var deferred = $.Deferred();
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl +"/_api/Web/Lists/GetByTitle('DistributorsListUpdated')/Items?$select=ID,EncodedAbsUrl,BaseURL,DistributorLogo,Distributor_x0020_ID",
        method: "GET",
        type: 'get', 
        async: false,       
        headers: {
            "accept": "application/json;odata=verbose",
            "content-Type": "application/json;odata=verbose"
        },
        success: function(result) {         
            deferred.resolve(result);
            console.log(result);
            
            $.each(result.d.results, function(index, row){

            UpdateListItemUsingItemId(row["ID"],row["EncodedAbsUrl"]); 

            });


        },
        error: function(result){               
            deferred.reject(result);
        }
    }); // Ajax list items
    
     return deferred.promise();

  };  

Update List Item Code

var UpdateListItemUsingItemId = function (Id,dLogo) {
    var deferred = $.Deferred();  
    getBase64Image(dLogo)
    var _listItem = {
            "__metadata": { 'type': 'SP.Data.DistributorsListUpdatedListItem' },            
            
            "BaseURL" : distlogo  
        }

  
    $.ajax({
        url:_spPageContextInfo.webAbsoluteUrl +"/_api/Web/Lists/GetByTitle('DistributorsListUpdated')/GetItemById("+ Id +")",       
        method: 'PATCH',
        async: false,
        data: JSON.stringify(_listItem),
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose",
            "X-Http-Method": "PATCH",
            "If-Match": "*"
        },
        success: function (data) {          
            deferred.resolve(data);
        },
        error: function (err) {
            deferred.reject(err);
        }
    }); // ajax | POST      
    return deferred.promise();    
}; // updateListItem() | Ends!

Code for base64 conversion

function getBase64Image(dLogo) {

  var canvas = document.createElement("CANVAS");
  var ctx = canvas.getContext("2d");
  ctx.clearRect( 0 , 0 , canvas.width, canvas.height );
  ctx.fillStyle="#FFFFFF";
  ctx.fillRect(0 , 0 , canvas.width, canvas.height);
  var img = new Image();
  
  img.crossOrigin = 'Anonymous';
  
  img.onload = function(){
  
   canvas.width = img.width;
   canvas.height = img.height;
   ctx.drawImage(img, 0, 0);
   
   var dataURL = canvas.toDataURL("image/jpeg");
   //alert(dataURL);
   //return dataURL;
   distlogo = dataURL;
   canvas = null;
   
  };

  
   img.src = dLogo;
}

 });

The base64 conversion code works fine when we pass a URL from a textbox control to the function , However fails and returns blank when passed dynamically from the response array.

The working format of the base64 string is

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAg

Would really appreciate if anyone could help me fix the issue so that all the URLs in the list could be converted to base64 URL to be used in a PDF.

Please let me know if more details are needed.

Thanks in Advance

Was it helpful?

Solution

Here are some points needs to modify:

  1. Update List Item needs to use Post method and MERGE X-Http-Method (Not PATCH)
  2. If want to convert DistributorLogo to Base64URL, use DistributorLogo instead of EncodedAbsUrl.

3.canvas.toDataURL is async request, needs a callback action to get the base 64 string before updating list item.

  1. The BaseURL field should be a Multi-Line text field, othewise will throw 500 error.

Here is the modified code snippet based on the point above (Update with canvas method):

 <script type="text/javascript">

        GetItemId();
       
        function UpdateListItemUsingItemId(Id, dLogo) {
            var deferred = $.Deferred();
            convertImgToBase64URL(dLogo, function (base64Img) {
                console.log(base64Img);
                var _listItem = {
                    "__metadata": { 'type': 'SP.Data.DistributorsListUpdatedListItem' },

                    "BaseURL": base64Img
                }


                $.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('DistributorsListUpdated')/Items(" + Id + ")",
                    method: 'POST',
                    async: false,
                    data: JSON.stringify(_listItem),
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "content-Type": "application/json;odata=verbose",
                        "X-Http-Method": "MERGE",
                        "If-Match": "*"
                    },
                    success: function (data) {
                        deferred.resolve(data);
                    },
                    error: function (err) {
                        deferred.reject(err);
                    }
                });
                return deferred.promise();
            });
        };

        function GetItemId() {
            //debugger;
            var deferred = $.Deferred();
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('DistributorsListUpdated')/Items?$select=ID,BaseURL,DistributorLogo",
                method: "GET",
                type: 'GET',
                async: false,
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-Type": "application/json;odata=verbose"
                },
                success: function (result) {
                    deferred.resolve(result);
                    $.each(result.d.results, function (index, row) {
                        UpdateListItemUsingItemId(row["ID"], row["DistributorLogo"]);

                    });


                },
                error: function (result) {
                    deferred.reject(result);
                }
            }); // Ajax list items

            return deferred.promise();

        };
        function convertImgToBase64URL(url, callback, outputFormat) {
            var img = new Image();
            img.crossOrigin = 'Anonymous';
            img.onload = function () {
                var canvas = document.createElement('CANVAS'),
                    ctx = canvas.getContext('2d'), dataURL;
                canvas.height = img.height;
                canvas.width = img.width;
                ctx.drawImage(img, 0, 0);
                dataURL = canvas.toDataURL(outputFormat);
                callback(dataURL);
                canvas = null;
            };
            img.src = url;
        }
    </script>

   

Here is the result capture:

enter image description here

Reference:

JavaScript Convert an image to a base64 url base64.js

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top