Uploading Attachments to SharePoint Lists Using REST

In a previous post, I walked through Uploading Attachments to SharePoint Lists Using SPServices. Well, in the “modern” world, I want to use REST whenever I can, especially with SharePoint Online.

Add an attachmentI ran into a challenge figuring out how to make an attachment upload work in an AngularJS project. There are dozens of blog posts and articles out there about uploading files to SharePoint, and some of them even mention attachments. But I found that not a single one of the worked for me. It was driving me nuts. I could upload a file, but it was corrupt when it got there. Images didn’t look like images, Excel couldn’t open XLSX files, etc.

I reached out to Julie Turner (@jfj1997) and asked for help, but as is often the case, when you’re not as immersed in something it’s tough to get the context right. She gave me some excellent pointers, but I ended up traversing some of the same unfruitful ground with her.

Finally I decided to break things down into the simplest example possible, much like I did in my earlier post with SOAP. I created a test page called UploadTEST with a Content Editor Web Part pointing to UploadText.html, below:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>

<input id="my-attachments" type="file" fileread="run.AttachmentData" fileinfo="run.AttachmentInfo" />

<script type="text/javascript" src="/sites/MySiteCollection/_catalogs/masterpage/_MyProject/js/UploadTEST.js"></script>

Like I said, I wanted to keep it simple. Here’s what I’m doing:

  • In line 1, I load a recent version of jQuery from cdnjs. On the theory that Angular just adds another layer of complexity, I wanted to try just jQuery, which is useful for its $.ajax function, among many other things.
  • In line 3, I’ve got an input field with type=”file”. In “modern” browsers, this gives us a familiar file picker.
  • In line 5, I’m loading my script file called UploadTest.js, below:
$(document).ready(function() {

 var ID = 1;
 var listname = "UploadTEST";

 $("#my-attachments").change(function() {

  var file = $(this)[0].files[0];

  var getFileBuffer = function(file) {

   var deferred = $.Deferred();
   var reader = new FileReader();

   reader.onload = function(e) {
    deferred.resolve(e.target.result);
   }

   reader.onerror = function(e) {
    deferred.reject(e.target.error);
   }

   reader.readAsArrayBuffer(file);

   return deferred.promise();
  };

  getFileBuffer(file).then(function(buffer) {

   $.ajax({
    url: _spPageContextInfo.webAbsoluteUrl +
     "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')",
    method: 'POST',
    data: buffer,
    processData: false,
    headers: {
     "Accept": "application/json; odata=verbose",
     "content-type": "application/json; odata=verbose",
     "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
     "content-length": buffer.byteLength
    }
   });

  });

 });
});

Here’s how this works – and yes, it does work!

  • I’ve got everything wrapped in a $(document).ready() to ensure the page is fully loaded before my script runs.
  • Lines 3-4 just set up some variables I could use for testing to keep things simple.
  • In line 6, I bind to the change event for the input field. Whenever the user chooses a file in the dialog, this event will fire.
  • In line 8, I’m getting the information about the file selected from the input element.
  • Lines 10-26 is the same getFileBuffer function I used with SOAP; it’s where we use a FileReader to get the contents of the selected file into a buffer.
  • The function in lines 28-42 runs when the file contents have been fully read. The getFileBuffer function returns a promise, and that promise is resolved when the function has gotten all of the file contents. With a large file, this could take a little while, and by using a promise we avoid getting ahead of ourselves. Here we make the REST call that uploads the attachment.
    • The URL ends up looking something like: “/my/site/path/_api/web/lists/getbytitle(‘UploadTEST’)/items(1)/AttachmentFiles/add(FileName=’boo.txt’)”
    • The method is a POST because we’re writing data to SharePoint
    • The data parameter contains the “payload”, which is the buffer returned from the getFileBuffer function.
    • The headers basically tell the server what we’re up to:
      • Accept doesn’t really come into play here unless we get a result back, but it says “send me back json and be verbose”
      • content-type is similar, but tells the server what it is getting from us
      • X-RequestDigest is the magic string from the page that tells the server we are who it thinks we are
      • content-length tells the server how many bytes it should expect

This worked for me on a basic Custom List (UploadTEST). So now I knew it was possible to upload an attachment using REST.

I took my logic and shoved it back into my AngularJS page, and it still worked! However, when I switched from $.ajax to AngularJS’s $http, I was back to corrupt files again. I’m still not sure why that is the case, but since I’m loading jQuery for some other things, anyway, I’ve decided to stick with $.ajax for now instead. If anyone reading this has an idea why $http would cause a problem, I’d love to hear about it.

Once again, I’m hoping my beating my head against this saves some folks some time. Ideally there would be actual documentation for the REST endpoints that would explain how to do things. Unfortunately, if there is for this, I can’t find it. I’d also love to know if /add allows any other parameters, particularly whether I can overwrote the attachment if one of the same name is already there. Maybe another day.

From the SPServices Discussions: Why Should I Bother to Learn XSLT?

Client Server DiagramHere’s a question from gdavis321 from the good old SPServices discussions. In most cases, I just answer the questions in situ, but occasionally – as you frequent readers know – I realize what I’m writing feels more like a blog post, so I move it over here.

It seems that Spservices (thank you for this god send) can do anything that you might want to do with a content query webpart or other webpart… am I missing something? Why should I bother to learn XSLT?

It’s a fair question. As someone who loves using the Data View Web Part (DVWP) – which is XSL-based – the answer is, as always, it depends.

Doing everything client side isn’t always a great idea. For each specific requirement, you should look at whether it makes more sense to do the heavy processing on the server or client. There are many variables which go into this, like client machine capabilities, data volume, number of data sources, need to join data from different sources, skills on the development team, desired time to market, etc.

In SharePoint 2013, much of the processing has moved to the client side (often called Client Side Rendering, or CSR), so many people think that we should just process everything client side now. I worry about this sort of myopia.

Client machines – meaning the machine sitting on your desk or in your lap or hand rather than the server, which sits in a data center somewhere – have better and better capabilities. Yet in many organizations, you may still see Windows XP machines with 1Gb of RAM – or worse!

Additionally, client side processing may mean moving a huge volume of data from the server to the client in order to roll it up, for example. If you’re moving thousands of rows (items) to make one calculation, it *can* feel sluggish on client machine without a lot of oomph.

So client side libraries like SPServices or KnockoutJS or AngularJS (among many others) are fantastic for some things, not so fantastic for others.

When it comes to the JavaScript versus XSL question, both approaches should be part of your toolset. Sometimes good old XSL will be an excellent call if you can do some of the heavy lifting on the server, then pass the results to the client for further processing. The output need not be just nicely formatted list views, but could be sent in such a format as to make the client side processing easy to start up upon page load. My approach is often to ship the data to the browser via a DVWP and then process it further with jQuery on the client.

The mix of what happens where is on a spectrum, too, depending on what you need to do. You might roll up tens of thousands of items in a DVWP and then request items from two or three other lists from the client as the page loads to optimize your architecture.

Yup, there’s that architecture word. A good SharePoint architect will know when to use each of the tools in the toolkit, and JavaScript and XSL are just two of many.

Keep in mind that because “it depends”, your mileage may vary in any and all of this: cavete architectus.