ASP.NET文件上传

本文详细探讨了在ASP.NET环境中实现文件上传的多种方案,包括使用Ajax调用接口、保存文件到服务器并通过session读取、直接利用form表单提交等方法,并提供了从前端到后端的完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求

需求:前端当前展示有一个列表信息,点击导入,将导入信息加载到列表中,导入信息不入数据库。

解决方案1

      通过Ajax调用接口,处理后将数据封装返回页面,再进行数据渲染。
失败原因:页面列表的数据是由服务端进行渲染,页面无法加载事件。

-------------------------------------------------------------------------------------------------------------------

解决方案2

      通过ajax调用接口,接口内容为将接收到的file文件保存到服务器,将信息保存到session中。返回成功后再进行 重定向 get请求,请求新接口,接口内容为读取session中存储的file文件进行解析内容,将解析过后的内容保存到对象当中,进而return View(对象),重新返回到新页面。(未进行测试)。

-------------------------------------------------------------------------------------------------------------------

解决方案3

      因为想通过js获取文件的绝对路径失败。(文件上传的路径被加密,目前通过js无法获取)

-------------------------------------------------------------------------------------------------------------------

解决方案4

既然异步已经走不通了,还是回到了初始的上传方式,利用form表单提交文件,将文件保存在服务器中,再读取数据,将读取的数据进行存储到对象格式中,通过return view(对象),返回界面中。

-------------------------------------------------------------------------------------------------------------------

前端代码

CSHTML

<form id="myOoForm" action="/Index" method="post" enctype="multipart/form-data">
    <label id="uploadlabel">
        <span>导入</span>
        <input id="upOoFile" type="file"  onchange="upfileDayOof(this)"  />
    </label>
</form>

JavaScript

function upfileDayOof(Oo) {
    var file = $(Oo).val();
    var strFileName = file.replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi, "$1");  //正则表达式获取文件名,不带后缀
    var FileExt = file.replace(/.+\./, "");   //正则表达式获取后缀
    //正则后的文件名
    var fileName = strFileName + "." + FileExt;
	//TODO 根据业务自增内容,比如判断文件格式是否正确。。。
    //form ID myOoForm ---表单提交
    $("#myOoForm").submit();
    $(Oo).val('');
}

后端代码

.NET

		[HttpPost]
        public ActionResult Index(HttpPostedFileBase myFile)
        {

          
            ///     ##########################
            ///       根据所需业务逻辑添加内容
            ///     ##########################

            //获取# 文件
            if(myFile == null)
            {
                myFile = Request.Files["upOoFile"];
            }

            //增加文件标识
            string strDate = DateTime.Now.ToString("ddMMyyyy_HHmmss");
            //文件名称
            string fullFileName = strDate + myFile.FileName;
            //如果不存在就创建file文件夹
            if (Directory.Exists(Server.MapPath("~/Upload/")) == false)
            {
                Directory.CreateDirectory(Server.MapPath("~/Upload/"));
            }
            //获取保存到服务器的路径
            string savePath = Server.MapPath(string.Format("~/Upload/{0}", fullFileName));
            //将文件保存到服务器
            myFile.SaveAs(savePath);
            try
            {
                //获取数据缓存(数据集)
                DataSet  ds = ExcelHelper.DoExcel(savePath);

                ///     ##########################
                ///       根据所需业务逻辑添加内容
                ///     ##########################

                if (ds != null)
                {
                    int count = ds.Tables.Count;
                    if (count > 0)
                    {
                        //初始化业务数据
                        string name = "";
                        string job_number = "";
                        string startTime = "";
                        string endTime = "";
                        string leaveType = "";
                        string leaveReason = "";
                        for (int i = 0,len = ds.Tables[0].Rows.Count; i < len; i++)
                        {
                            //##############业务对象处理###########
							// 获取单元格内容,也可以通过[][]形式获取,更灵活。
                            job_number = ds.Tables[0].Rows[i]["工号"].ToString();
                            startTime =  ds.Tables[0].Rows[i]["开始时间"].ToString();
                            endTime = ds.Tables[0].Rows[i]["结束时间"].ToString();
                            leaveType = ds.Tables[0].Rows[i]["请假类型"].ToString();
                            leaveReason = ds.Tables[0].Rows[i]["请假理由"].ToString();
                        }
                    }
                }
                return View(存储数据的对象);
            }
            catch (Exception ex) {}
            finally {}
        }
-------------------------------------------------------------------------------------------------------------------

ExcelHelper

	/// <summary>
    /// <para>Excel导入工具类 </para>
    /// </summary>
    public class ExcelHelper
    {
        /// <summary>
        /// <para>解析excel文件</para>
        /// <para>@Parma realPath : 文件的在服务器中的绝对路径 </para>
        /// </summary>
        /// <param name="realPath">文件的在服务器中的绝对路径</param>
        /// <returns></returns>
        public static DataSet DoExcel(string realPath)
        {
            //  建立连接
            OleDbConnection conn = new OleDbConnection();
            //  表示要对访问数据源执行的sql语句或存储过程
            OleDbCommand cmd = new OleDbCommand();
            //  表示用于填充 System.Data.DataSet 和更新数据源的一组数据命令和一个数据库连接。
            OleDbDataAdapter da = new OleDbDataAdapter();
            //  数据在内存中的缓存
            DataSet ds = new DataSet();
            //  查询语句
            string query = null;
            //  连接驱动
            string connString = "";

            //  文件后缀
            string strExtension = System.IO.Path.GetExtension(realPath);

            if (strExtension.Trim() == ".xls")
            {
                //xls 的驱动
                connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + realPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"");
            }
            else if (strExtension.Trim() == ".xlsx")
            {
                //xlsx 的驱动
                connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + realPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"");
            }

            //  ACCESS 语句
            query = "SELECT * FROM [Sheet1$]";
            //  获得连接
            conn = new OleDbConnection(connString);

            try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    //打开连接
                    conn.Open();
                }
                cmd = new OleDbCommand(query, conn);
                da = new OleDbDataAdapter(cmd);
                ds = new DataSet();
                //执行刷新数据
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                //TODO 异常处理
                return ds;
            }
            finally
            {
                //释放流
                da.Dispose();
                conn.Close();
                conn.Dispose();

            }
            return ds;
        }
    }
-------------------------------------------------------------------------------------------------------------------

Alt

Mon 06 Mon 13 Mon 20 已完成 进行中 计划一 计划二 现有任务 ...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值