Microsoft 365 – SharePoint Online – Uploading file using REST API – resolving error – code:-2130575251 Microsoft.SharePoint.SPException – The security validation for this page is invalid and might be corrupted. Please use your web browsers Back button to try your operation again

fig : Microsoft 365 - SharePoint online - PnP script editor webpart - error while uploading document in SharePoint using REST API
fig : Microsoft 365 - SharePoint online - PnP script editor webpart - error while uploading document in SharePoint using REST API

Hi All,

Greetings for the day!!! Today new issue 🙂 and Solution 🙂

Background

  • For one of my project, I am working on document upload functionality using REST API – <WEB URL>/_api/Web/GetFolderByServerRelativeUrl(‘<DOCUMENT LIBRARY NAME>’)/Files/add(url='<FILE NAME>’)
  • I have my respective JS file and HTML code
  • I am using PnP Script Editor web part to reference the my HTML code and JS file
  • PnP script editor webpart can be downloaded from – https://handsontek.net/Downloads/Power%20BI/pnp-script-editor.zip.
  • I have extracted the “pnp-script-editor.zip” and uploaded package to my app catalog site as
fig : Microsoft 365 - SharePoint online - Uploading PnP script editor package to AppCatalog
fig : Microsoft 365 – SharePoint online – Uploading PnP script editor package to AppCatalog
  • I am using “File” HTML input control for getting file from the file system and button to call “upuploadDocument” method which uses SharePoint REST API to upload document as

<input id = "documents" type = "file" multiple />

<button  id = "fileuploadbutton" type = "button" onclick = "uploadDocument()">Upload Document</button>

  • Code referred in PnP script editor webpart

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script type="text/javascript" src="https://knowledgejunction1.sharepoint.com/SiteAssets/fileupload.js"></script>
<div>   <input id = "documents" type = "file" multiple />  
       <br/>   
        <div>       
           <button  id = "fileuploadbutton" type = "button" onclick = "uploadDocument()">Upload Document</button>
           </div>  
           </div>

  • Few steps are
    • Getting all files from “File” HTML input control
    • Getting local file as array buffer

//uploadFile - file object - read from "File" HTML input control
function getFileArrayBuffer(uploadFile) {  
    //alert("getFileBuffer called");
 var deferred = jQuery.Deferred();
 var fileReader = new FileReader();
 fileReader.onloadend = function(e) {
     deferred.resolve(e.target.result);
 }
 fileReader.onerror = function(e) {
    //alert("Get file buffer failed");
     deferred.reject(e.target.error);
 }
 fileReader.readAsArrayBuffer(uploadFile);
 return deferred.promise();
}

  • Once we have file array buffer, we will call our SharePoint REST API as
  • We are using REST API – <WEB URL>/_api/Web/GetFolderByServerRelativeUrl(<DocumentLibray name>)/Files/add(url=<file name>)”

//uploadFile - file object - read from "File" HTML input control
var file = getFileArrayBuffer(fileObject);

// Adding file to SharePoint  
        file.done(function(fileArrayBuffer) {  
            $.ajax({  
                url: "https://knowledgejunction1.sharepoint.com/_api/Web/GetFolderByServerRelativeUrl('Demolibrary')/Files/add(url='PrashamSabadra_Speaker_.docx')",  
                type: "POST",  
                data: fileArrayBuffer,  
                processData: false,  
                async: false,  
                headers: {  
                    "accept": "application/json;odata=verbose",  
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),  
                },  
                success: function(data) {  
                    alert("File uploaded successfully")
;
                },  
                error: function(error) {  
                    alert(error.responseText);
                }  
            });  
        });  
       }

fig : Microsoft 365 - SharePoint online - PnP script editor webpart - referring our HTML and JS file
fig : Microsoft 365 – SharePoint online – PnP script editor webpart – referring our HTML and JS file
  • As we executing code, clicking on “Upload Document” we get an exception

Issue / Error

{“error”:{“code”:”-2130575251, Microsoft.SharePoint.SPException”,”message”:{“lang”:”en-US”,”value”:”The security validation for this page is invalid and might be corrupted. Please use your web browser’s Back button to try your operation again.”}}}

fig : Microsoft 365 - SharePoint online - PnP script editor webpart - error while uploading document in SharePoint using REST API
fig : Microsoft 365 – SharePoint online – PnP script editor webpart – error while uploading document in SharePoint using REST API

  • This error generally occurs when we dont include request digest in request or missing or expired form digest
  •  If we do not using OAuth to authorize our requests, we require the server’s request form digest value as the value of the X-RequestDigest header
  • But I have already included request digest in request as

headers: {  
                    "accept": "application/json;odata=verbose",  
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),  
                }

Solution

function getFormDigest(webUrl) {
    return $.ajax({
        url: webUrl + "/_api/contextinfo",
        method: "POST",
        headers: { "Accept": "application/json; odata=verbose" }
    });
}

return getFormDigest("https://knowledgejunction1.sharepoint.com").then(function (data) {
 //uploadFile - file object - read from "File" HTML input control
var file = getFileArrayBuffer(fileObject);

// Adding file to SharePoint  
        file.done(function(fileArrayBuffer) {  
            $.ajax({  
                url: "https://knowledgejunction1.sharepoint.com/_api/Web/GetFolderByServerRelativeUrl('Demolibrary')/Files/add(url='PrashamSabadra_Speaker_.docx')",  
                type: "POST",  
                data: fileArrayBuffer,  
                processData: false,  
                async: false,  
                headers: {  
                    "accept": "application/json;odata=verbose",  
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),  
                },  
                success: function(data) {  
                    alert("File uploaded successfully")
;
                },  
                error: function(error) {  
                    alert(error.responseText);
                }  
            });  
        }); }

I hope this will help and will save time

Thanks for reading ! HAVE a FANTASTICE LEARNING AHEAD 🙂 LIFE IS BEAUTIFUL 🙂

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Microsoft 365

Subscribe now to keep reading and get access to the full archive.

Continue reading