File uploader control in each row of html table

Noman Soofi 1 Reputation point
2023-03-08T06:20:41.2566667+00:00

I am generating the rows dynamically in a HTML table on a button click. In each row there is a HTML file uploader control. Let say If I create 3 rows and on each row I browse the 3 different files for uploading. when I click submit button, I am being unable to get the file and upload in SharePoint list. For getting each row day, I am executing a loop.

please help me to get out of this problem.

Below is my code:


 <table class="myTable">
        <thead>
            <tr>
                <th>Uploading</th>
                <th>Team Name</th>
                <th>Cricketer Name</th>
                <th>Score</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="myBody">
            <tr>
                <td>
                    <input type="file" id="doc_upload0" name="doc_upload" onchange="return validateSize(this, this.id)"/></td>
                <td>
                    <input type="text" class="txtTeam" name='txtTeam0' placeholder="Enter Team Name"></td>
                <td>
                    <input type="text" class="txtTeam" name='txtPlayer0' placeholder="Enter Player Name"></td>
                <td>
                    <input type="text" class="txtTeam" name='txtBowler0' placeholder="Enter Bowler Name"></td>
                <td>
                    <button type="button" class="btnDelete" > - </button></td>
            </tr>
        </tbody>
    </table>
    
    <p><button type="button" id="btnsave" class="btn btn-success" onclick="saverecord()">Save</button></p>

<script>

    var t;
    var rowHtml;
    $(document).ready(function () {

        var ID = 0;
        
        t = $("#myTable").DataTable();

        $("#addrows").click(function () {

            ID += 1;
            rowHtml = "<tr><td><input type='file' id='doc_upload" + ID + "' name='doc_upload' onchange='return validateSize(this, this.id)' /></td>" +
                "<td><input type='text' name='txtTeam" + ID + "' placeholder='Enter Team Name' /></td>" +
                "<td><input type='text' name='txtPlayer" + ID + "' placeholder='Enter Player Name' /></td>" +
                "<td><input type='text' name='txtBowler" + ID + "' placeholder='Enter Bowler Name' /></td>" +
                "<td><button type='button' class='btnDelete' > - </button></td></tr>";

            $("#myBody").append(rowHtml);
        });

        $(document).on('click', 'button.btnDelete', function () {
            $(this).closest('tr').remove();
            return false;
        });

    });

    function saverecord() {

        var row = $('#myBody tr');
        var TotalRows = $('#myBody tr').length;
        serviceUri = "http://mysite/_vti_bin/Service1.svc/UATObservations";

        for (var i = 0; i <= 1; i++) {

            var fu_control = row[i].cells[0].getElementsByTagName('input')[0].value;

            var vData = {

                //ID: $("#RowID_IH").val(),
                TeamName: row[i].cells[1].getElementsByTagName('input')[0].value,
                PlayerName: row[i].cells[2].getElementsByTagName('input')[0].value,
                BowlerName: row[i].cells[3].getElementsByTagName('input')[0].value
            }

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8", // this
                dataType: "json", // and this
                url: serviceUri,
                data: JSON.stringify(vData),
                headers: { "Accept": "application/json; odata=verbose" },
                success:
                function (response) {
                    console.log(response);

                    if (fu_control != '')
                    {
                        readFile(response, "PWA_UATObservation_Documents", fu_control);  // doc librayname 
                    }

                    alert("record saved successfully.");

                },
                error:
                function (err) {
                    console.log(err);
                }
            });

            
        }


    function readFile(response, dlname, ctrlname) {
        //Get File Input Control and read the file name  
        //var element = document.getElementById("Attached_detailed");
        var element = document.getElementById(ctrlname);
        var file = element.files[0];
        var ReqID = response;
        //var documentlib = 'Detailed Requirement Document';
        var documentlib = dlname;
        var parts = element.value.split("\\");
        var fileName = parts[parts.length - 1];
        //Read File contents using file reader  
        var reader = new FileReader();
        reader.onload = function (e) {
            uploadFile(e.target.result, fileName, documentlib, "1");
            //uploadFile(e.target.result, fileName, documentlib, ReqID);
        }
        reader.onerror = function (e) {
            alert(e.target.error);
        }
        reader.readAsArrayBuffer(file);
    }

    function uploadFile(arrayBuffer, fileName, documentlib, ReqID) {
        //Get Client Context,Web and List object.  
        var clientContext = new SP.ClientContext();
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle(documentlib);
        //Convert the file contents into base64 data  
        var bytes = new Uint8Array(arrayBuffer);
        var i, length, out = '';
        for (i = 0, length = bytes.length; i < length; i += 1) {
            out += String.fromCharCode(bytes[i]);
        }
        var base64 = btoa(out);
        //Create FileCreationInformation object using the read file data  
        var createInfo = new SP.FileCreationInformation();
        createInfo.set_content(base64);
        createInfo.set_url(fileName);
        //Add the file to the library  
        debugger;
        var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
        var myListItem = uploadedDocument.get_listItemAllFields();
        myListItem.set_item("ReqID", ReqID.toString());
        myListItem.update();
        //Load client context and execcute the batch  
        clientContext.load(uploadedDocument);
        clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
    }

    function validateSize(input, ctrlname) {
        const fileSize = input.files[0].size / 1024 / 1024; // in MiB
        if (fileSize > 10) {
            alert('File size exceeds 10 MB');
            $("#" + ctrlname + "").css("border", "2px solid red");
            return false;
            // $(file).val(''); //for clearing with Jquery
        } else {
            $("#" + ctrlname + "").css("border", "");
            return true;
            // Proceed further
        }
    }
</script>
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,621 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
866 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,668 questions
{count} votes