Upload a File to Content Server using REST and Javascript

This is an example how to upload a file using JavaScript and REST.

This example uploads the file c:\test.txt with the name of “MyFile123” under the folder with the node id 485336. This snipped relies on a previous login. The subtype of the file to be uploaded is “document” (144). The authorization token is saved under the variable name of “otcsticket”.

This example does not consider any categories (mantadory or not). We’ll discuss this in a later post.

6 Steps:

  1. Declare all variables needed. This is done by defining the array bodyData. At least there must be the subtpe, the parent_id, the name and the local file name.
  2. Fire an AJAX request to the URL, where your content server is, Use “api/v1/nodes” as REST command.
  3. Put the authorization ticket in the header field
  4. Put the bodyData in the data field
  5. Set the Mime Type to “application/x-www-form-urlencoded”
  6. If the request is done, process the “success” or the “failure” clauses

Put some nice HTML around it, add the authorization code and then you are done.

(At least for this example. Normally, you should provide some name check for the node name)

function upload() {
  var bodyData = {
        type: 144,
        parent_id: 485336,
        name: "Myfile123",
        file: "c:\\test.txt"
        }
      formData = new FormData();
  formData.append( "body", JSON.stringify( bodyData ) );

  formData.append( "file", "c:\\test.txt" );
  return $.ajax( {
    type: "POST",
    url: "http://[yourserver/yourcs/cs.exe/api/v1/nodes",
    data: bodyData,
    headers: { otcsticket: otcsticket },
    beforeSend: function( xhr ) {    
    xhr.overrideMimeType( "application/x-www-form-urlencoded" )
    }
  } ).then( function ( response ) {
    alert("Success")
  }, function ( jqxhr ) {
    alert("failure")
  } );
}