1.前端:
放置浏览按钮
<div class="row inner_table text-center"> <input id="fileId" type="file" name="fileString" class="file "> </div>
2. JS:
注册浏览按钮的事件
var ChoseFile = function () { $("input[name=fileString]") .change(function () { var filePath = $("[name='fileString']"); //读取文件内容 var formData = new FormData(); formData.append('file[]', filePath[0].files[0]); $.ajax({ url: "XXXXXXXX入库链接", type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { alert("上传成功"); }, error: function (returndata) { alert("上传失败"); } }); }); }
3 controller:
[CustomAuthorize(AuthType.Authrozied)] public JsonResult DataImport(FormCollection form) { string zipDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "templateFiles"); string masterFile = Path.Combine(zipDir, "template" + ".csv"); if (!Directory.Exists(zipDir)) { Directory.CreateDirectory(zipDir); } var file = Request.Files[0];
//上传 file.SaveAs(masterFile); DataTable dt = GetCSVToData(masterFile); List<ScheduleTableInfo> infos = new List<ScheduleTableInfo>(); foreach (DataRow dataRow in dt.Rows) { ScheduleTableInfo info = new ScheduleTableInfo(); info.TemplateName = dataRow["标题名1"].ToString(); info.SumLevelName = dataRow["标题名2"].ToString(); infos.Add(info); } //执行入库操作 int value = _client.ImportData(infos); var jsonStr = JsonConvert.SerializeObject(infos, new DataTableConverter(), new JavaScriptDateTimeConverter()); jsonStr = jsonStr.Replace("\\n", "\r"); var result = Json(jsonStr, JsonRequestBehavior.AllowGet); return result; }
功能子函数:
private DataTable GetCSVToData(string strCsvPath, bool hasHeader = true, bool needLineNo = false) { CSVReader csvReader = null; try { csvReader = new CSVReader(strCsvPath, FileEncoding.GetType(strCsvPath)); DataTable dt = csvReader.GetTable(1, -1, hasHeader); return dt; } catch (Exception ex) { LogService.Debug("解析csv文件错误:" + ex); return null; } finally { if (csvReader != null) { csvReader.Dispose(); } } }
导入文件,获取文件位置