0

Excel 工作表要在 MVC5 中单击按钮上传时读取。上传的 excel 文件名使用 AJAX 方法传递给操作。这里文件变量在发布方法中获取空值。在这里,如何在下面的 ajax 方法中将选定的文件作为 HttpPostedFileBase 传递。`

 <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 "";
    }
4

1 回答 1

0

我得到了解决方案。更改代码如

<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(); }

于 2016-02-11T05:06:10.533 回答