0

I have a input type file button inside a dialog box that I would like to get that file input(an image) and send that image data as a fileupload or some kind of format so I can convert it to my webmethod as a parameter so that it can convert that image into a binary to store it in my access database.

This is my code so far javascript side:

 $(document).ready(function () {
        $.ajax({
            url: '<%=ResolveUrl("GetEmployee.aspx") %>',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                var table = $('#datatable').DataTable({
                    data: data,
                    columns: [
                        { 'data': 'Id' },
                        { 'data': 'image' },
                        { 'data': 'lastName' },
                        { 'data': 'firstName' },
                        { 'data': 'jobTitle' },
                        {
                            'data': 'StartDate',
                            'render': function (jsonDate) {
                                var date = new Date(parseInt(jsonDate.substr(6)));
                                var month = date.getMonth() + 1;
                                return month + "/" + date.getDate() + "/" + date.getFullYear();
                            }
                        },
                        {
                            'data': 'EndDate',
                            'render': function (jsonDate) {
                                var date = new Date(parseInt(jsonDate.substr(6)));
                                var month = date.getMonth() + 1;
                                return month + "/" + date.getDate() + "/" + date.getFullYear();
                            }
                        },
                        {
                            'data': null,
                            'render': function (data, type, row) {
                                return '<button id="editBtn" onclick="editClick(this)" type="button">Edit</button>'
                            }
                        },
                        {
                            'data': null,
                            'render': function (data, type, row) {
                                return '<button id="' + row.id + '" onclick="deleteClick(this)" type="button">Delete</button>'
                            }
                        }
                    ]
                });
            }
        });

        $('#dialog').dialog({
            width: 600,
            height: 500,
            autoOpen: false,
            title: 'Employee Form',
            buttons: {
                'Submit': function () {
                    var lastName = $('#lName').val();
                    var firstName = $('#fName').val();
                    var jobTitle = $('#jobTitle').val();
                    var startDate = $('#startDate').val();
                    var endDate = $('#endDate').val();
                    $.ajax({
                        url: '<%=ResolveUrl("AddEmployee.aspx/AddEmp") %>',
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({ lName: lastName, fName: firstName, jobTitle: jobTitle, startDate: startDate, endDate: endDate }),
                        success: function (data) {

                        }
                    });
                }
            }
        });
        $('#add').click(function () {
            $('#dialog').dialog('open');
        });
    });


    function editClick(obj) {
        var employeeID = $(obj).closest('tr').find('td:first').html();
        var lastName = $(obj).closest('tr').find('td:nth-child(3)').html();
        var firstName = $(obj).closest('tr').find('td:nth-child(4)').html();
        var jobTitle = $(obj).closest('tr').find('td:nth-child(5)').html();
        var startDate = $(obj).closest('tr').find('td:nth-child(6)').html();
        var endDate = $(obj).closest('tr').find('td:nth-child(7)').html();
        console.log(startDate);

        if (employeeID != null) {
            $('#lName').val(lastName);
            $('#fName').val(firstName);
            $('#jobTitle').val(jobTitle);
            $('#startDate').val(startDate);
            $('#endDate').val(endDate);

            $('#dialog').dialog({
                width: 600,
                height: 500,
                autoOpen: false,
                title: 'Employee Form',
                buttons: {
                    'Edit': function () {
                        $.ajax({
                            url: '<%=ResolveUrl("EditEmployee.aspx/EditEmpl") %>',
                            type: 'POST',
                            contentType: 'application/json; charset=utf-8',
                            data: JSON.stringify({ lName: $('#lName').val(), fName: $('#fName').val(), jobTitle: $('#jobTitle').val(), startDate: $('#startDate').val(), endDate: $('#endDate').val(), id: employeeID }),
                            success: function (data) {

                            }
                        });
                    }
                }

            });
            $('#dialog').dialog('open');
        }
    }


    function deleteClick(obj) {
        var employeeID = $(obj).closest('tr').find('td:first').html();
        //alert(employeeID);
        //alert(lastName);
        var data = '{ id:' + employeeID + '}';
        $.ajax({
            url: '<%=ResolveUrl("DeleteEmployee.aspx/DeleteRecords") %>',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: data,
            success: function (data) {

            }
        });
    }
</script>
<title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div style="border:1px solid black; padding:3px; width:1200px; margin:auto">
            <table id="datatable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Picture</th>
                        <th>Last Name</th>
                        <th>First Name</th>
                        <th>Job Position</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th></th>
                        <th></th>
                    </tr>
                </thead>
            </table>
                <button id="add" type="button">Add</button>
            <div id="dialog">
            <div style="padding-top:10px; padding-left:10px">
                 <label>Last Name: </label>
                 <input type="text" id="lName" placeholder="Last Name"/><br />
            </div>
            <div style="padding-top:10px; padding-left:10px">
                <label>First Name: </label>
                <input type="text" id="fName" placeholder="First Name"/><br />
            </div>
            <div style="padding-top:10px">
                <label>Job Position: </label>
                <input type="text" id="jobTitle" placeholder="Job Title" /><br />
            </div>
            <div style="padding-top:10px; padding-left:15px">
                <label>Start Date: </label>
                <input type="date" id="startDate"/><br />
            </div>
            <div style="padding-top:10px; padding-left:19px">
                <label>End Date: </label>
                <input type="date" id="endDate"/><br />
            </div>
            <div style="padding-top:10px">
                <input type="file" id="fileUpload"/><br /> 
            </div>

        </div>
    </div>
<div>

</div>


</form>
</body>
</html>

What I'm trying to do was something like this on the web method side to convert into byte:

[WebMethod]
public static void addEmployees(FileUpload picture, string lName, string, fName, string jobTitle, DateTime startDate, DateTime endDate) {
        string filePath = picture.PostedFile.FileName;
        string fileName = Path.GetFileName(filePath);
        string extension = Path.GetExtension(fileName);

        Stream fs = picture.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
}

I left out the database insertion code as it's pretty irrelevant to my problem as I have no trouble inserting the other fields like first name, last name, and such. I just have trouble figuring out how to send a input type file image using ajax to my webmethod as a parameter so i can convert it and store it in my database.

Any help is appreciated!

SC.Cee
  • 237
  • 1
  • 4
  • 14
  • You have to use `.ashx` Generic Handler for that – Hemal Feb 10 '17 at 07:08
  • where is the code that sends the file? – madalinivascu Feb 10 '17 at 07:11
  • That is the part i'm having trouble with. I don't know how to send the file within my dialog submit function that when i click submit, it will grab the input file data and send it as a parameter. – SC.Cee Feb 10 '17 at 07:12
  • Probably this answer helps you out: http://stackoverflow.com/a/8758614/1040225 ... or probably this: http://codepedia.info/upload-image-using-jquery-ajax-asp-net-c-sharp/. Other than that, you would need to change the contentType of your ajax call to multipart/formdata and receive the binaries server-sided (f.e. using a generic handler). Let me know if you are stuck on any of this! – konrad_pe Feb 10 '17 at 07:33
  • @konrad_pe Hi, thanks that looks helpful just a question though, what is the data type being passed for input files? as i need to pass that on as a parameter to my webmethod. E.g. public static void addEmployee(datatype image,.....) – SC.Cee Feb 10 '17 at 07:45
  • Hmm not really, the postedFiles should be (depending on details of your implementation!) in your httpContext (e.g. ```HttpContext.Current.Request.Files;```). But as said, this depends on how you implement this also on your client side. Best thing to do is take a look at various fileUpload solutions/tutorials, pick one, try to get it running. And then check back, once something isn't working properly. – konrad_pe Feb 10 '17 at 08:03
  • @konrad_pe All the examples I've found so far requires you to put contentType: false, and processData:fasle, but if i do that i wont be able to pass in my other params that i need for insertion like the last name and first name. Any suggestions for this? – SC.Cee Feb 10 '17 at 08:59

0 Answers0