For adding attachment via ajax I used this code from https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest : and added "for" and iffy function to make it unique to all files.
for (var i = 0; i < files.length; i++) {
// IFFY to save the current index
(function (x) {
var file = files[x];
lastFileName = file.name;
var fileName = Date.now() + file.name;
var getFileBuffer = function (file) {
//alert('in getFileBuffer');
var deferred = NWF$.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) {
//alert(buffer);
NWF$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items('" + idVal + "' ) / AttachmentFiles / add(FileName = '" + fileName + "')",
method: 'POST',
body: "Contents of file",
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
}, //end headers
success: function (data) {
console.log(data);
var fileUrl = _spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl;
NWF$('#displayFiles tr:last').after('<tr><td><a class="fileLink" href="' + fileUrl + '">' + lastFileName + '</a> '
+ '</td><td><a class="removeHyper">מחיקה ×</a></td></tr>');
filesItems.push(_spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl);
NWF$('#' + filesList).text(converAddressToString(filesItems))
},
error: function (data) {
console.log("err " + data.d);
}
});
})
})(i)
The problem is that I need to add a folder of the attachement id before.
NWF$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items",
method: "POST",
body: { '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': _spPageContextInfo.webAbsoluteUrl + '/Lists/stamList/Attachments/' +idVal},
headers: {
"ACCEPT": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
}, //end headers
success: function (data) {
console.log(data);
},
error: function(data){
console.log("err");
}
});
And THAT is not working :( that's why the item is not added. What do you think? how to add folder named idval in the attachment?