0

I have a SharePoint hosted html file with a form that I use to add a new list item to a SP list via the REST API. I am also reading data from the list using AngularJS for both reading and writing to list. In the code below I am trying to upload files to the list. Adding new list items work with no problem. The problem is uploading files. I think the form is closing without the files getting uploaded and I don't know how to pause it to wait for files to be uploaded. Or my code is not correctly uploading to SP. How should I be calling the uploading files function to upload the files to the list? Thank you.

This is what I have for the file upload element in the form. I am using the getFileData() to read the file names and display them in the div with id of files.

<form ng-submit="updateList()">
...
<div>
    <input type="file" class="form-control input-lg" name="attachments" id="attachments" multiple onchange="getFileData()">
</div> 
<div id="files"></div>
...
</form>

This is my controller code.

// BEGIN controller code
app.controller('supportController',
    function($scope, $http) {

    // BEGIN upload file code
    function uploadFile(listname, ID, file) {
        var formdigest = $scope.getFormDigest();

        var getFileBuffer = function(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();
        };
    
        getFileBuffer(file).then(function(buffer) {
            alert(file.name);

            $.ajax({
                url: "https://.../_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')",
                method: 'POST',
                async: false,
                data: buffer,
                processData: false,
                headers: {
                    "Accept": "application/json; odata=verbose",
                    "content-type": "application/json; odata=verbose",
                    "X-RequestDigest": formdigest
    
                },
                success: function(data) {
                    console.log("file attached to the list item successfully...");
                },
                error: function(data) {
    
                    console.log("Error message: " + JSON.stringify(data.responseJSON.error));
                }
    
            });
    
        });
    
    }; // END file upload code 

     ...

    // BEGIN code to post a new entry to list
    $scope.updateList = function() {

        ...

        jQuery.ajax({
            url: "https://.../_api/web/lists/GetByTitle('EU34SupportTracker')/items",
            method: "POST",
            data: JSON.stringify({
                '__metadata' : {'type': 'SP.Data.EU34SupportTrackerListItem'},
                'Title': title,
                ...
                'Ticket_x0020_number': externaltt

            }),
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": formdigest
            },
            success: function(data) {
                console.log("entry created successfully...");
                console.log(data.d.ID);
                // CALL UPLOAD FILE FUNCTION HERE
                $.When(uploadFile('EU34SupportTracker', data.d.ID, $("#attachments")[0].files[0])).then(location.reload());
                //location.reload();
            },
            error: function(data) {
                //console.log("#__REQUESTDIGEST".val());
                console.log("Error message: " + JSON.stringify(data.responseJSON.error));
            }
        });

       
        // close modal
        $('#myModal').modal('hide');
        location.reload();
      
    }; // END code to upload to list

1 Answer 1

0

I think the location.reload() in sucess function is your problem since this is asynchronous execution you can rather use it has $.When(uploadfiles()).then(location.reload())

you can also pass multiple ajax call as arguments to when, so this can also be done as

$.When($ajax1(), $.ajax2()).then(location.reaload());

https://api.jquery.com/jquery.when/

1
  • I edited the code to show that new entry but unfortunately that did not work. But, thanks for the feedback.
    – martinbshp
    Commented Nov 19, 2020 at 7:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.