ajax+ .NET 实现文件上传保存以及.NET NPOI实现对文件的读取

来源

.NET FileUpload控件也可以是实现但,是Scriptmanager后端调用前端函数,刷新和调用不到的问题,让我很无奈,于是自己按照网上写了如下的方法。

HTML

<div class="row">
                    <div class="form-group">
                        <p class="col-md-3 control-label text-right" style="font-size: 24px;">请上传要添加的文件:</p>
                        <div class="col-md-3  control-label" style="padding-left: 0px; padding-right: 0px;">
                            <input type="file" id="exampleInputFile3" name="exampleInputFile3" accept="application/vnd.ms-excel,.csv">
                        </div>
                        <div class="col-md-1">
                            <button class="btn btn-default" type="button" id="UpLoad"> <i class="fa fa-cloud-upload bigger-120"></i> 上传</button>
                        </div>
                        <div class="col-md-4  control-label  nopadding">文件(*.xls;*.xlsx;),大小不得超过1M</div>
                    </div>
                </div>

JS

  $('#UpLoad').click(function() {

        var f = $('#exampleInputFile3')[0].files[0];
        if (typeof(f) == "undefined") {
            alert('请选择要上传的文件');
            return;
        }
        if (f.size > 1024000) {
            alert('文件太大!');
            return;
        }
        //var formData = new FormData();
        //formData.append("Excelfile", $('#exampleInputFile3')[0].files[0]);
        $.ajaxFileUpload({
            url: 'Url',
            secureuri: false,
            fileElementId: 'exampleInputFile3',
            type: 'POST',
            dataType: 'json',
            success: function(data, status) {


                var status = data.dataStatus;
                // 0  失败
                // 1  成功
                // 2  参数名称错误
                // 3  产品名称重复
            
                if (status == "0") {
                    alert("文件上传失败!");
                }
                if (status == "2") {
                    alert("参数名称错误!");
                }
                if (status == "3") {
                    alert("产品名称错误!");
                }

            },
            error: function(data, status, e) {
                alert(e);
            }
        });
    });

这里注意一点,需要下载ajaxFileUpload插件,其次fileElementId是input type = file时的ID,但是不知道为什么,只写ID时,后台找不到这些文件,name属性和ID属性保持一致时,后台才得到我要的文件。

.NET ashx

 context.Response.ContentType = "text/plain";
            HttpFileCollection files = context.Request.Files;
            string file = "";
            int dataStatus = 0;
            //状态码
            #region 
            // 0  失败
            // 1  成功
            // 2  参数名称错误
            // 3  产品名称重复
            #endregion
            string Code = "";//新添加的参数名称
            if (files.Count > 0)
            {
                string filepath = "../Products/DaoruFiles/";
                if (Directory.Exists(context.Server.MapPath(filepath)) == false)    //如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(context.Server.MapPath(filepath));
                }
                string fileExtension = Path.GetExtension(files[0].FileName);
                string fileName = "Daoru" + CreatePasswordHash(files[0].FileName, 4);
                string virpath = filepath + fileName + fileExtension;//这是存到服务器上的虚拟路径
                 file = files[0].FileName;
                //ExcelUpload.PostedFile.SaveAs(Server.MapPath(virpath));//转换成服务器上的物理路径,保存图片
                files[0].SaveAs(context.Server.MapPath(virpath));
                //分析文件
                using (FileStream fsRead = File.OpenRead(context.Server.MapPath(virpath)))
                {
                    //读取第一个WorkSheet
                    IWorkbook wk = new XSSFWorkbook(fsRead);
                    ISheet sheet = wk.GetSheetAt(0);
                    //读取Project Name
                    IRow rowname = sheet.GetRow(13);
                    string projectName = rowname.GetCell(5).ToString();
                    //生成电子器件信息
                    LEM_Electronic eleone = new LEM_Electronic();
                   
                    //读取特定行
                    foreach (int i in arr)
                    {
                        IRow currenRow = sheet.GetRow(i);
                        遍历一行中所有的单元格
                        //for (int c = 1; c < currenRow.LastCellNum; c++)
                        //{
                        //    string AttrNam = currenRow.GetCell(c).ToString();
                        //}
                        //获得产品参数名称
                        string AttrName = currenRow.GetCell(1).ToString();
                        LEM_Attr attr = LEM_AttrDAL.GetByName(AttrName);
                        if (attr == null)
                        {
                            // ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "key", "alert('文档中存在参数表中没有的参数,请先添加参数" + AttrName + "')", true);
                            dataStatus = 2;
                            return;
                        }
                        ICell cell = currenRow.GetCell(12);
                        //主要的值
                        CellRangeAddress ad = new CellRangeAddress(i, i, 12, 14);
                        //判断是否是合并单元格
                        if (sheet.IsMergedRegion(ad))
                        {
                            //若是,则认为LEM为text类型
                            string attrtext = cell.ToString();
                            LEM_ElectronicAttr Eattr = new LEM_ElectronicAttr();
                            Eattr.ElectronicCode = eleone.ElectronicCode;
                            Eattr.ElectronicName = eleone.ElectronicName;
                            Eattr.ElectronicAttrCode = attr.ElectronicAttrCode;
                            Eattr.ElectronicAttrName = attr.ElectronicAttrName;
                            Eattr.Attrtext = attrtext;
                            Eattr.AttrComment = currenRow.GetCell(17).ToString();
                            LEM_ElectronicAttrDAL.Insert(Eattr);
                        }
                        else
                        {
                            decimal attrmin = Convert.ToDecimal(currenRow.GetCell(12).NumericCellValue);
                            decimal attrtyp = Convert.ToDecimal(currenRow.GetCell(13).NumericCellValue);
                            decimal attrmax = Convert.ToDecimal(currenRow.GetCell(14).NumericCellValue);
                            LEM_ElectronicAttr Eattr = new LEM_ElectronicAttr();
                            Eattr.ElectronicCode = eleone.ElectronicCode;
                            Eattr.ElectronicName = eleone.ElectronicName;
                            Eattr.ElectronicAttrCode = attr.ElectronicAttrCode;
                            Eattr.ElectronicAttrName = attr.ElectronicAttrName;
                            Eattr.AttrMin = attrmin;
                            Eattr.AttrTyp = attrtyp;
                            Eattr.AttrMax = attrmax;
                            Eattr.ElectronicUnit = currenRow.GetCell(15).ToString();
                            Eattr.AttrComment = currenRow.GetCell(17).ToString();
                            LEM_ElectronicAttrDAL.Insert(Eattr);
                        }
                    }

                    返回前端显示列表,成功
                    //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "key", "alert('上传成功!')", true);
                    dataStatus = 1;
                }
                context.Response.Write(JsonConvert.SerializeObject(new { file = file, dataStatus = dataStatus,Code=Code}));
            }

以上实现了Ajax加.NET后端 文件上传的方式。
补充: input file 时的属性
accept:可以判断接受哪种类型的文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值