1

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

2
  • If you are trying to encode the value of the DistributorLogo column, why are you passing the value of the EncodedAbsUrl column into your UpdateListItemUsingItemId function? Also, I see you commented out the return from your getBase64Image function, but if you don't return anything from that function, how does "BaseURL" : distlogo have any value when you build your update payload? Commented Feb 17, 2021 at 20:00
  • @DylanCristy Thank you for the feedback , Yes I was testing the code with a few modifications , Even when I uncomment the return statement and use it like "var get = getBase64Image(dLogo)" , it returns null. I'll keep your suggestions in mind :)
    – Vivek
    Commented Feb 18, 2021 at 6:29

1 Answer 1

0

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

7
  • Thanks a lot Jerry , Would edit the code as per your suggestions and test it out :)
    – Vivek
    Commented Feb 18, 2021 at 6:30
  • You are welcome. You can try the new function "toDataUrl" and updateListItem in the callback function, this will return the valid base64 string.
    – Jerry
    Commented Feb 18, 2021 at 7:13
  • Thank you for the proactive help jerry , I have replied to your answer on github as it helps me explain the roadblock in comments along with the screenshots , Would you mind checking the answer there?
    – Vivek
    Commented Feb 18, 2021 at 7:44
  • Check the update in GitHub, I will also update the answer with canvas method.
    – Jerry
    Commented Feb 18, 2021 at 7:53
  • Thanks a lot Jerry , everything seems to be working as expected now :) Would continue testing
    – Vivek
    Commented Feb 18, 2021 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.