前言
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