SharePoint Upload Files To Document Library Using Rest API

48 views Asked by At

I have a form "developed by JS" and this form has two sections fields related to other 2 forms and each of them file input. when the user clicks on submit the form should update the same request with specific status then take the value from the first section create an item in other document library then upload multiple files to the same item then take the new item id and update the current item with the URL then do the same to other section. the issue is the files uploading sometimes upload all files and sometimes upload some of the files not all and sometimes doesn't upload any of them. Note: i tried to log or alert the response but not appear and sometimes appear.

This my code

for (var i = 0; i < files.length; i++) {
    var formData = new FormData();
    console.log(files[i]);
    formData.append('fileInput', files[i]);
    var branchName = KYCCompliance.getBranchNameFromCode(branchCode);
    var siteUrl = `${KYCCompliance.webUrl}/_api/web/GetFolderByServerRelativeUrl('/sites/KYC/${KYCCompliance.CardsUploadData.DocStorage.DocListInternalName}${branchName}/${onlineBankingObj.Title}')/files/add(url='${files[i].name}',overwrite=true)')`
    var headers = new Headers();
    headers.append('X-RequestDigest', $("#__REQUESTDIGEST").val());
    $.ajax({
        url: siteUrl,
        type: 'POST',
        async: true,
        data: formData,
        processData: false,

        contentType: false,
        headers: {
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        },
        success:function (response) {
            // alert(`File ${files[i].name} uploaded successfully.`)
            return console.log('File uploaded successfully. Response: ' + response);
        },
        error: function (error) {
            // alert(`Error uploading file: ${files[i].name}`  + error.statusText)
            return console.log('Error uploading file: ' + error.statusText);
        }
    });
}
0

There are 0 answers