MohammadReza Roohafza

طبقه بندی موضوعی
نویسندگان

۱ مطلب در دی ۱۳۹۷ ثبت شده است

استفاده از JSON در MVC انتقال فایل

يكشنبه, ۹ دی ۱۳۹۷، ۰۳:۵۱ ب.ظ

HTM


<input   value="ارسال فایل " onclick="return file_check()  " />


<script>

    function file_check()

    {

        if ($("#fileupload").val() == '')

        {

            $("#message").html("فایلی انتخاب نشده است");

            return false;

        }

        else

        {

        send_file()

        }

    }


        function send_file() {




            // Checking whether FormData is available in browser

            if (window.FormData !== undefined) {


                var fileUpload = $("#fileupload").get(0);

                var files = fileUpload.files;


                // Create FormData object

                var fileData = new FormData();


                // Looping over all files and add it to FormData object

                for (var i = 0; i < files.length; i++) {

                    fileData.append(files[i].name, files[i]);

                }


                // Adding one more key to FormData object

                fileData.append('returnUrl', '@Request.Url.ToString()');

//create parameter for key

                fileData.append('id', '@Request.QueryString["id"].ToString()');


                $.ajax({

                    url: '/controlname/actionname',

                    type: "POST",

                    contentType: false, // Not to set any content header

                    processData: false, // Not to process data

                    data: fileData


                    ,

                    success: function (result) {

                        alert(result);

                    },

                    error: function (err) {

                        alert(err.statusText);

                    }

                });

            } else {

                alert("FormData is not supported.");

            }


    }


</script>


in Model 

        [HttpPost]
        public ActionResult import(HttpPostedFileBase fileupload, string inv_id, string returnUrl)
        {
            fileupload = Request.Files[0];
            inv_id = Request.Params["inv_id"].ToString();
            returnUrl = Request.Params["returnUrl"].ToString();
            // fileupload = Request.Files["data"];
            if (fileupload.ContentLength > 0)
            {
                try
                {

                    var file_name = DateTime.Now.Date.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() +DateTime.Now.Millisecond.ToString();  //Path.GetFileName(fileupload.FileName);
                    var path = Path.Combine(Server.MapPath("~/Uploads"), file_name);
                    fileupload.SaveAs(path);
                    // Connection String to Excel Workbook
                    string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
                    OleDbConnection connection = new OleDbConnection();
                    connection.ConnectionString = excelConnectionString;
                    OleDbCommand command = new OleDbCommand(" select   subinvoice_gcode,  subinvoice_dis,  subinvoice_count,  unit_code, subinvoice_unitprice, subinvoice_discount,  subinvoice_dus,  subinvoice_tax   from [import$]  where len(subinvoice_dis)>0", connection);
                    connection.Open();
                    // Create DbDataReader to Data Worksheet
                    DbDataReader dr = command.ExecuteReader();
                    // SQL Server Connection String
                    string sqlConnectionString = @"Data Source=197.0.0.1;Initial Catalog=pro;User ID=sa;Password=111951";
                    // Bulk Copy to SQL Server 
                    SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
                    bulkInsert.DestinationTableName = "temp_data";
                    bulkInsert.WriteToServer(dr);

                }
                catch (Exception ex)
                {

                 return Json("انتقال اطلاعات جدول  با مشکل مواجه گردیده است" +"\r"+ex.Message, JsonRequestBehavior.AllowGet);
                }

            }
                 return Json("انتقال اطلاعات جدول  با موفقیت انجام گردید" , JsonRequestBehavior.AllowGet);
    


        }



  • محمد رضا روح افزا