在Asp.net使用layui.upload上传文件

前言

LayUI中的layui.upload可以使用各种样式,比传统的Asp.net中FileUpload更为简洁方便。
这里参考了一位博主的链接:Asp.net中Excel数据导入到SQL Server

前端

首先定义一个上传按钮:

<button style="float:right;margin-right:0px;margin-bottom:30px" type="button" class="layui-btn" id="upload"><i class="layui-icon"></i></button><br />

上传按钮

初始化layui.upload功能

layui.use('upload', function () {
   
var $ = layui.jquery
, upload = layui.upload;//指定允许上传的文件类型
	upload.render({
   
	    elem: '#upload'
	    , url: 'UploadExcel.ashx' //改成您自己的上传接口
	    , accept: 'file' //普通文件
	    , done: function (res) {
   
	        console.log(res);
	        //如果上传失败
	        if (res.code > 0) {
   
	            if (res.code == 2) {
   
	                return layer.msg('Only .xlsx file types can be uploaded.');
	            } else {
   
	                return layer.msg('Upload failed! Please check the network.');
	            }
	        } else if (res.code == 0) {
   
	            return layer.msg('Uploaded successfully!');
	        }
	    }
	});
});

后端代码

先上传文件到服务器中

if (HttpContext.Current.Request.Files.Count > 0)
{
   
    string fileExtension = System.IO.Path.GetExtension(HttpContext.Current.Request.Files[0].FileName).ToLower();
    if (fileExtension != ".xlsx")
    {
   
        Json = "{\"code\": 2,\"msg\": \"\",\"data\": {\"src\": \"http://cdn.layui.com/123.jpg\"}}";
        context.Response.Write(Json);
    }
    else
    {
   
        try
        {
   
            //得到客户端上传的文件
            HttpPostedFile file = HttpContext.Current.Request.Files[0];
            //服务器端要保存的路径
            string filePath = HttpContext.Current.Server.MapPath("~/excel/") + file.FileName;
            file.SaveAs(filePath);
            //返回结果
            Json = "{\"code\": 0,\"msg\": \"\",\"data\": {\"src\": \"http://cdn.layui.com/123.jpg\"}}";
            //读取Excel文件并填写到一个DateSet中
            DataSet ds = GetExcelData(filePath, fileExtension);
            InsertDB(ds);
            context.Response.Write(Json
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值