Resturl = {} / _api / Sharepoint Upload

The code I'one thousand going to prove you today will show you how you tin upload a file to a certificate library using REST. This solution could be used inside a Sandbox awarding.

To upload files, information technology is much better to utilize Rest than the SharePoint API. The main reason is that SharePoint JSOM/CSOM can only upload files a maximum size of 1.5MB, where Residuum is good up to 2GB.

My example here has a simple GUI, it is an Upload form, which allows the user to pick from a listing the site they wish to upload the file to, a file upload box, and an Upload button.

HTML Code.

<SharePoint:FormDigest runat="server"/> <div>    <label id="lblInfo" class="label" for="ProposalSiteUrl">Please enter your Site Collection URL or exit blank to upload file to this Site Collection certificate library:</label> </div> <div>    <select id="ProposalSiteUrl" grade="dropdown" title="Select a site">                     <option value="http://intranet.cannonfodder.local">This Site</selection>                     <option value="http://intranet.cannonfodder.local/sites/teamsite1">Team Site ane</pick>                     <option value="http://intranet.cannonfodder.local/sites/teamsite2">Team Site two</option>                     <option value="http://intranet.cannonfodder.local/sites/teamsite3">Team Site 3</option>       </select> </div> <div form="div">         <input id="AttachmentUploadField" blazon="file" size="98"/>         <input id="AttachAttachmentButton" class="button" onclick="CannonFodder.Utilities.SaveAttachment();" type="button" value="Upload"/> </div> <div course="div">          <label id="lblResult" class="result"></label> </div>        

The user can select from the dropdown a site to send the file to. Select the file using the file picker and click Upload. You tin can meet in this example I have difficult coded the choice values for the dropdown list. Whatsoever results pass or failed will be displayed to the user using the lblResult label.

JavaScript

This code will require JQuery for grabbing the element values from the page and to perform JQuery Ajax request. Ensure that your folio has JQuery loaded. In this example I grabbing JQuery from Google.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.ane.one/jquery.min.js"></script>        

Personally, JavaScript isn't my preferred programming language and I'm trying to write better JavaScript. I'm ensuring I'm not making information technology office of the Global namespace, and using battle methods etc. Therefore in this instance here you should notice this a adept practice writing JavaScript.
First I'one thousand going to namespace my JavaScript Methods.

var CannonFodder = CannonFodder || {}; CannonFodder.Utilities = function(){ var currentDlg;  //Code to write in hither.  return {       SaveAttachment:saveAttachment  }; }();        

The above slice of code, will create a namespace called CannonFodder.Utilities with one public method called SaveAttachment which calls the private method saveAttachement. We haven't written saveAttachment yet. We volition write a bunch of functions inside the section where I have commented '//Code to write in here'. The first ane will exist saveAttachement. (Detect small 'southward' for save) This method will be the only method in this section that tin can be called from outside of CannonFodder.Utilities. The variable currentDlg
is a global variable for the scope of CannonFodder.Utilities. It is so I can display a waiting dialog screen to the user. This isn't necessary for this code to work, it just gives the demo a nicer user experience.

The saveAttachment method

var saveAttachment = function(){     //Validate if the upload file has a file selected.     if(!validated()){             jQuery('#lblResult').text("Please choose a file!");             return;     }          //Dialog variables     var dlgTitle;     var dlgMsg;     var dlgWidth;     var dlgHeight;     dlgTitle = "Uploading Your File...";     dlgMsg = "<br />Please wait whilst your file is being uploaded<br /><br />Please do not shut your browser window.";     dlgHeight = 300;     dlgWidth = 500;              //Create Dialog box.    if (currentDlg == null) {            currentDlg = SP.UI.ModalDialog.showWaitScreenWithNoClose(dlgTitle, dlgMsg, dlgHeight, dlgWidth);    }     //Get File            var file = jQuery("#AttachmentUploadField")[0].files[0];     //Upload the file    uploadFile(file); };        

The lawmaking above doesn't practice much, information technology commencement calls a validation method (yet to write) to check if the user has selected a file to upload. If not, it updates the lblresult text to inform the user they must upload a file. If validation passes, nosotros fix a dialog box to inform the user that the upload is taking place (it will have a long time for a 2GB file). Adjacent nosotros brandish the dialog to the user, grab the file and passes information technology to the uploadFile method.

The validated method

var validated = function(){    var file = jQuery("#AttachmentUploadField")[0].files[0];    if(file == goose egg){                   return fake;   }   else{     return truthful;   } };        

The validated method grabs the Upload control and checks if there is a file available. If it is at that place then the function returns true, else it returns false.

The uploadFile method

var uploadFile = function (file) {     proposalSiteUrl = jQuery('#ProposalSiteUrl choice:selected').val();                      if (proposalSiteUrl == _spPageContextInfo.webAbsoluteUrl) {         uploadFileLocal(file);     }     else{         uploadFileCrossSite(file, proposalSiteUrl);     } };        

Our upload file still isn't the actual code that uploads the file to the given URL. Here I'm checking if the site I'one thousand uploading to is the aforementioned Site Collection I'yard running my upload folio from or not. If it is, and then I can practice a very simple upload (uploadFIleLocal). If I demand to upload to a different Site Drove, and then I will be required to perform a cross site call (uploadFileCrossSite).

The uploadFileLocal method

To explain this, I am going to show this method in bits and explain each section.

var uploadFileLocal = office (file) {       var digest = jQuery("#__REQUESTDIGEST").val();       var webUrl = _spPageContextInfo.webAbsoluteUrl;       var libraryName = "Documents";        var reader = new FileReader();       var arrayBuffer;        

First we need to prepare all our variables. The assimilate request is important, it is a customer side token to validate post backs to SharePoint to prevent attacks where the user might be tricked into posting data back to the server. It is unique to a user and a site. It is only valid for a limited time. The first line gets the current asking digest from the page. This assimilate is required in our ajax post request when we upload the file. The other variables are pretty standard, spider web url, the library name to upload to, a file reader and assortment buffer.

        reader.onload = function (e) {             arrayBuffer = reader.result;              url = webUrl + "/_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/files/add together(url=@TargetFileName,overwrite='true')?" +                "@TargetLibrary='" + libraryName + "'" +                "&@TargetFileName='" + file.name + "'";              //JQuery Ajax call here         };        reader.readAsArrayBuffer(file);   };        

The next part of the uploadFileLocal role that continues straight after var arrayBuffer. Our reader needs to read in the file, and on the onload event, we demand to prepare our Residue url to past into the JQuery ajax request. (The JQuery Ajax call is shown in the next piece of code). The reader.onload part doesn't fire until after reader.readAsArrayBuffer(file) is called. The Rest url uses two parameters @TargetLibrary and @TargetFileName, the actual file information is put into arraryBuffer and used in the JQuery Ajax call.

         jQuery.ajax({         url: url,        type: "Post",        data: arrayBuffer,     headers: {             "Accept": "application/json; odata=verbose",             "10-RequestDigest": digest             },     contentType: "application/json;odata=verbose", processData: false,     success: role () {             jQuery('#lblResult').text("Successfully uploaded file locally.");             if (currentDlg != null) {                         currentDlg.close();             }          },      error: office (arr, fault) {                jQuery('#lblResult').text("Error uploading file locally.");                if (currentDlg != naught) {                       currentDlg.close();                }           } });        

Insert the above code in the previous snippet where the comment //JQuery Ajax call here is. This is a typical Ajax call using JQuery. http://api.jquery.com/jquery.ajax/ We pass in our REST url, country that it's a Mail service request, and gear up the data to our file arrayBuffer. Our headers show that the call is a json call, and here we pass in the request digest we obtained in the very first variable of the uploadfileLocal part. The contentType and processData are standard for this type of call. Lastly I take created a success and mistake callbacks, with inline functions. The functions are like, both updating the lblResult text with a success or neglect message, and then close the dialog that is on prove to the user. In the error office we could use the error variable to obtain the actual error message and brandish information technology to the user.

This concludes uploading a file to the aforementioned site. All the same if you endeavour to use the same lawmaking to upload to a different site it will fail. The reason is all to practise with the digest request. As I stated before, this is a customer side token that is unique to the user and site. Therefore when you lot try to access a different site to what you are on, you will exist passing an invalid digest request. You first need to obtain the digest asking for the other site earlier you lot can upload/mail service data to it. Please notation: The user volition need contribute admission to the site to exist able to upload a file.

The uploadFileCrossSite method

var uploadFileCrossSite = function (file, webUrl) {         url = webUrl + "/_api/contextinfo";         jQuery.ajax({             url: url,             type: "Mail service",             headers: {                 "Have": "application/json; odata=verbose"             },             contentType: "application/json;odata=verbose",             success: function (data) {                var digest = data.d.GetContextWebInformation.FormDigestValue;                 var libraryName = "Documents";                  var reader = new FileReader();                 var arrayBuffer;                  reader.onload = function (eastward) {                     arrayBuffer = reader.upshot;                      url = webUrl + "/_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/files/add(url=@TargetFileName,overwrite='true')?" +                        "@TargetLibrary='" + libraryName + "'" +                        "&@TargetFileName='" + file.proper name + "'";                      jQuery.ajax({                         url: url,                         type: "Postal service",                         data: arrayBuffer,                         headers: {                             "Have": "application/json; odata=verbose",                             "10-RequestDigest": assimilate                         },                         contentType: "application/json;odata=verbose",                         processData: simulated,                         success: function () {                         jQuery('#lblResult').text("Successfully uploaded file to different site.");                           if (currentDlg != null) {                               currentDlg.close();                               }                         },                         error: function () {                           jQuery('#lblResult').text("Error uploading file to different site.");                           if (currentDlg != null) {                               currentDlg.close();                               }                          }                     });                 };                  reader.readAsArrayBuffer(file);              },        error: function () {             jQuery('#lblResult').text("Fault accessing other site.");                if (currentDlg != null) {                    currentDlg.close();               }           }       });  };        

The uploadFileCrossSite code I have shown equally whole, mainly considering I have explained virtually of information technology in the uploadFileLocal function above. The lines I've highlighted i-11 is a JQuery Ajax telephone call into the target site. By requesting the context info, we can obtain the request digest of the target site in the success handler, data.d.GetContextWebInformation.FormDigestValue. We can and so use this value to pass in as the digest to upload the file to the target site. The code to upload the file at present is identical as before, obtaining the reader, calling the onload outcome, so on the success of the Ajax request we update the lblResult with a success message and close the dialog displayed.

The final error:function() call lines 53-59 highlighted at the bottom of the code is the error callback if at that place is an error contacting the target site for the request digest.

I can now test the form, I've selected my second team site, and selected a document DemoWordDoc3.docx to upload. I've then clicked the Upload push button.

The file dialog appears in the center of the screen then the user knows something is happening.

When the file has been uploaded, the user gets the message that information technology has successfully uploaded.

If I check out my Team Site 2, yous can see that the DemoWordDoc3 is in the Documents library.

You lot tin can obtain my upload page from my OneDrive. To get into your SharePoint site, it is easiest simply to copy it in using SharePoint Designer.

http://1drv.ms/1tcIDIQ

fischertrustold.blogspot.com

Source: https://cann0nf0dder.wordpress.com/2014/09/07/using-rest-to-upload-a-file-to-document-library-including-different-site-collection/

0 Response to "Resturl = {} / _api / Sharepoint Upload"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel