jeudi 26 mars 2015

Upload list item attachment using JSOM



I am trying to upload list item attachment using the below code. There is no error in the code and all the variables are present with proper values but in uploadFile method it goes to error handler and says File not found. Can anyone help?



function UploadAttachment() {
this.filename = $('input[type=file]').val().split('\\').pop();
var args = window.frameElement.dialogArgs;
this.itemId = args.ItemId; //$.QueryString["ItemId"];
this.clientContext = new SP.ClientContext.get_current();
var outReachList = clientContext.get_web().get_lists().getByTitle('Outreach List');
this.listItem = outReachList.getItemById(itemId);
clientContext.load(listItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.HasListItemAttachment), Function.createDelegate(this, this.GetAllAttachmentsFailed));
}

function HasListItemAttachment() {
var attachmentFolderUrl = String.format('{0}/Attachments/{1}',listItem.get_fieldValues()['FileDirRef'], itemId);
console.log(attachmentFolderUrl);
this.attachmentFolder = clientContext.get_web().getFolderByServerRelativeUrl(attachmentFolderUrl);
clientContext.load(attachmentFolder);
clientContext.executeQueryAsync(Function.createDelegate(this, this.uploadFile), Function.createDelegate(this, GetAllAttachmentsFailed));
}

//function to actually upload file
function uploadFile() {
var file = document.getElementById("customFileUploadControl").files[0];
getFileBuffer(file).then( function(buffer) {
var bytes = new Uint8Array(buffer);
var content = new SP.Base64EncodedByteArray(); //base64 encoding
for (var b = 0; b < bytes.length; b++) {
content.append(bytes[b]);
}
var createInfo = new SP.FileCreationInformation();
createInfo.set_content(content); //setting the content of the new file
createInfo.set_url(filename);
attachmentFolder.add(createInfo);
clientContext.executeQueryAsync(Function.createDelegate(this, uploadFileSuccess), Function.createDelegate(this, GetAllAttachmentsFailed));
});
}

function uploadFileSuccess() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK);
}

function GetAllAttachmentsFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function getFileBuffer(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();
}







0 commentaires:

Enregistrer un commentaire