0

I'm trying to perform a POST request containing a picture to a document server via ajax out of my mobile JavaScript application.

My ajax call with the required cmis data looks like the following:

var cmisInfo = {
  'objectId': parentFolder,
  'cmisaction': 'createDocument',
  'propertyId[0]': 'cmis:name',
  'propertyValue[0]': filename,
  'propertyId[1]': 'cmis:objectTypeId',
  'propertyValue[1]': 'cmis:document'
};


$.ajax(rootFolder, {
  type: 'POST',
  data: cmisInfo,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    xhr.setRequestHeader('Authorization', "Basic dXNlcjpwdw==");
  }
}).done(function(response) {
  console.log("New File ID: " + response.properties["cmis:objectId"].value);
}).fail(function(jqXHR) {
  console.log(jqXHR.responseJSON.message);
});

The picture im trying to upload is present as a BASE64 string, fetched with a FileReader. Lets assume it's saved in the following variable:

var pictureBase64; // containing picture from filesystem in BASE64

My question now is, where to put pictureBase64 as content in my request? I suppose that such an object would be sent along in the data attribute within the ajax call normally, but in my case the data attribute is already used for the required cmis information. How can I send both?

Any help or hints would be appreciated!

c7n
  • 1,131
  • 16
  • 29

1 Answers1

0

Got it working with help from here and here.

To upload a picture from the file system to a document server, I had to send the data as FormData in the ajax call and append the image data like the following:

formData = new FormData;
formData.append('objectid', parentFolder);
formData.append('cmisaction', 'createDocument');
formData.append('propertyId[0]', 'cmis:name');
formData.append('propertyValue[0]', filename);
formData.append('propertyId[1]', 'cmis:objectTypeId');
formData.append('propertyValue[1]', 'cmis:document');
formData.append('_charset_', 'UTF-8');
formData.append('media', newBlob);

The newBlob is converted from the original pictureBase64, containing the image data as a base64 string:

cleanBase64 = pictureBase64.match(/,(.*)$/)[1];
binaryImage = atob(cleanBase64);
arrayBuffer = new ArrayBuffer(binaryImage.length);
uintArray = new Uint8Array(arrayBuffer);
i = 0;
while (i < binaryImage.length) {
  uintArray[i] = binaryImage.charCodeAt(i);
  i++;
}
blob = new Blob([uintArray], {
  type: "image/jpeg"
});
newBlob = blob.slice(0, blob.size, "image/jpeg");

At last processData: false and contentType: false have to be added to the ajaxcall to make it work.

Community
  • 1
  • 1
c7n
  • 1,131
  • 16
  • 29