JS实现文件自动上传
JS引用: <script type="text/javascript" src="~/bootstrap/js/fileinput.min.js"></script> <link href="~/bootstrap/css/fileinput.min.css" rel="stylesheet" /> <script src="~/Scripts/lib/jquery.json.js"></script> HTML: <input id="fileUpload" type="file" > JS: //自动上传文件-JS function initFileInput(ctrlName, uploadUrl) { var control = $('#' + ctrlName); control.fileinput({ language: 'zh', //设置语言 uploadUrl: uploadUrl, //上传的地址 (该方法需返回JSON字符串) allowedFileExtensions: ['xlsx', 'xls', 'txt'],//接收的文件后缀 showUpload: false, //是否显示上传按钮 showCaption: true,//是否显示标题 browseClass: "btn btn-primary", //按钮样式 //previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", uploadExtraData: { ID: "123" } }).on('filebatchselected', function (event, data, id, index) { $(this).fileinput("upload"); }).on("fileuploaded", function (event, data) { if (data.response) { //通过 data.response.Json对象属性 获得返回数据 errors = data.response.ErrorList; } }) } //上传JS初始化 $(function () { initFileInput("fileUpload", "Controllers/Action"); }); //获取上传文件弹窗关闭动作 $("#fileUpload").change(function () { alert("上传文件弹窗已关闭") }) 参考资料:http://www.oschina.net/code/snippet_269752_55899
C#后台保存处理:
//上传文件 string root = "~/Upload/Files/StorageOutFile/"; string path = Server.MapPath(root); string datePath = string.Empty; datePath += DateTime.Now.Year.ToString(); datePath += DateTime.Now.Month.ToString("D2"); datePath += DateTime.Now.Day.ToString("D2") + "/"; root += datePath; if (path != null) { path += datePath; if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } } string fileName = root + CurUser.StaffName + DateTime.Now.ToString("yyyyMMddhhmmssffff") + Path.GetExtension(Request.Files[0].FileName); string fileUrl = Server.MapPath(fileName);
//保存文件 Request.Files[0].SaveAs(fileUrl); //读取EXCEL DataSet ds = new DataSet(); Workbook workbook = new Workbook(fileUrl); Worksheet sheet = workbook.Worksheets[0]; Cells cells = sheet.Cells; DataTable tab = new DataTable(); for (int i = 0; i <= cells.MaxColumn; i++) { tab.Columns.Add(cells[0, i].StringValue.Trim(), typeof(System.String)); } for (int i = 1; i <= cells.MaxDataRow; i++) { DataRow dr = tab.NewRow(); for (int j = 0; j <= cells.MaxDataColumn; j++) { string data = cells[i, j].StringValue.Trim(); dr[j] = data; } tab.Rows.Add(dr); } ds.Tables.Add(tab); DataTable dt = ds.Tables[0];