Hi,
In office 365 site, I have a SharePoint CSOM code to upload the file as an attachment to a list. But the code randomly fails to upload. Some times the file will be uoloaded succesfully, but some times it fails. But I am very sure if I debug the code in browser, the upload never fails.
Please find the code below and let me know, whether anything goes wrong here.
function uploadFile(listName, id, file) {
var deferred = $.Deferred();
var fileName = file.name;
getFileBuffer(file).then(
function (buffer) {
var bytes = new Uint8Array(buffer);
var binary = '';
for (var b = 0; b < bytes.length; b++) {
binary += String.fromCharCode(bytes[b]);
}
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
//console.log(' File size:' + bytes.length);
$.getScript(scriptbase + "SP.RequestExecutor.js", function () {
var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
createitem.executeAsync({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='"+ file.name + "')",
method: "POST",
binaryStringRequestBody: true,
body: binary,
success: fsucc,
error: ferr,
state: "Update"
});
function fsucc(data) {
console.log(fileName + ' uploaded successfully');
deferred.resolve(data);
}
function ferr(data) {
//console.log(fileName + " not uploaded error");
//console.log(data.get_message());
deferred.reject(data);
}
});
},
function (err) {
deferred.reject(err);
}
);
return deferred.promise();
}
Chaitanya.