1

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">מחיקה &times</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?

1 Answer 1

1

This is the working code for uploading files to item :)

var filesItems = []

var file var table = "" var listName = "stamList" var item = NWF$("#getFile") NWF.FormFiller.Events.RegisterAfterReady(function () { NWF$("#getFile").on('change', function () { var idVal = NWF$("#" + itemID).val();

    var files = this.files;
    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");
        }

    });

    for (var i = 0; i < files.length; i++) {
        setTimeout((function (x) {
            var file = files[x];
            var 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">מחיקה &times</a></td></tr>');
                        filesItems.push(_spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl);
                        NWF$('#' + filesList).text(convertAddressToString(filesItems))
                    },
                    error: function (data) {
                        console.log("err " + data.d);
                    }
                });
            })
        })(i), 100*i);
        // IFFY to save the current index


    }
    NWF$("#displayFiles").on('click', '.removeHyper', function (e) {
        var idRow = NWF$(this).closest('tr').index() - 1;
        if (idRow >= 0) {
            console.log(idRow);
            filesItems.splice(idRow, 1)
            NWF$('#' + filesList).text(convertAddressToString(filesItems))
        }
        NWF$(this).closest('tr').remove()
    })

    function convertAddressToString(array) {
        return array.join('\n');
    }
})

})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.