0

The Excel sheet want to read while it upload on a button click in MVC5.The uploaded excel file name is passed into action using AJAX method.Here the file variable get null value in posted method. Here how can pass selected file as HttpPostedFileBase in the below ajax method. `

 <input style="display:none" type="file" id="fileupload1" />
     <button type="button"  onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
    <span style="display:none" id="spnName"></span>



$(function () {$("#fileupload1").change(function () {
    $("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));


    var file = $("#spnName").html();
              $.ajax({
        url: "UploadExcelForContractStaff",
        type: 'POST',
        data: JSON.stringify({ file: file }),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {

        }
    });


});
});`



  [AcceptVerbs(HttpVerbs.Post)]
    public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
    {
        StringBuilder strValidations = new StringBuilder(string.Empty);
        try
        {
            if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
               Path.GetFileName(uploadFile.FileName));
                uploadFile.SaveAs(filePath);
                DataSet ds = new DataSet();

                //A 32-bit provider which enables the use of

                string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";

                using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
                {
                    conn.Open();
                    using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
                    {
                        string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                        string query = "SELECT * FROM [" + sheetName + "]";
                        OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
                        //DataSet ds = new DataSet();
                        adapter.Fill(ds, "Items");
                        if (ds.Tables.Count > 0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    //Now we can insert this data to database...
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex) { }
        return "";
    }
Safeena
  • 395
  • 2
  • 7
  • 20

1 Answers1

0

I got solution. changed code like

<form enctype="multipart/form-data" id="frmUplaodFileAdd"> @Html.AntiForgeryToken() <input style="display:none" type="file" id="fileupload1" /> <button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button> <span style="display:none" id="spnName"></span> </form>

$.ajax({ url: "UploadFile", //Server script to process data type: 'POST', async: false, xhr: function () { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Check if upload property exists myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload } return myXhr; }, data: formData, //Options to tell jQuery not to process data or worry about content-type. cache: false, contentType: false, processData: false, success: function (data) { } });

[HttpPost] public ActionResult UploadFile(HttpPostedFileBase file) {return Json(); }

Safeena
  • 395
  • 2
  • 7
  • 20