上传模板读取,不必保存临时目录
前端代码
// 上传按钮点击事件
$("#uploadFile").click(function () {
var file = $('#inputFile').val().trim();
if (file == "") {
layer.msg("上传文件不能为空!");
return false;
}
var fileExt = file.substr(file.lastIndexOf(".")).toLowerCase();//获得文件后缀名
if (fileExt == '.csv' || fileExt == '.txt') {
$("#inputFileTable").ajaxSubmit({
url: getUrl('/aaaa/uploadFile', token),
type: "post",
enctype: "multipart/form-data",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.flag == 'success') {
// 刷新前端数据
$('#tb_departments').bootstrapTable('refresh');
layer.msg('上传成功!');
} else {
layer.msg(data.msg);
}
},
error: function (data) {
if (data.flag == "error") {
layer.msg(data.msg);
}
}
});
} else {
layer.msg("仅支持csv格式的文件!");
}
});
后台对应controller
主要是利用 InputStream inputStream = multipartFile.getInputStream();
/**
* 上传文件、解析文件内容、入库
*
* @param inputFile 上传文件
* @param auditDataSource 数据源
* @param request request
* @param res response
* @return
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody
Map<String, Object> uploadFile(@RequestParam(value = "inputFile", required = false) MultipartFile inputFile, String dataSource, HttpServletRequest request, HttpServletResponse res) {
Map<String, Object> mapResult = new HashMap<String, Object>();
InputStream inputStream = null;
try {
dataSource = new String(dataSource.getBytes("ISO-8859-1"), "UTF-8");
if (StringUtils.isBlank(dataSource)) {
mapResult.put("flag", "error");
mapResult.put("msg", "数据源类型异常!");
return mapResult;
}
if (inputFile == null) {
throw new Exception("未检测到上传文件!");
}
inputStream = inputFile.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
// 判断第一行表头
if (StringUtils.isBlank(line)) {
mapResult.put("flag", "error");
mapResult.put("msg", "文件为空");
return mapResult;
}
String[] splitOne = line.split(",", -1);
if (splitOne.length != cloArr.length) {
mapResult.put("flag", "error");
mapResult.put("msg", "文件表头长度异常");
return mapResult;
}
for (int i = 0; i < cloArr.length; i++) {
if (!cloArr[i].equals(splitOne[i])) {
mapResult.put("flag", "error");
mapResult.put("msg", "表头字段不合规:" + splitOne[i]);
return mapResult;
}
}
// 验证数据
int l = 1;
while ((line = reader.readLine()) != null) {
l++;
System.out.println(line);
}
inputStream.close();
mapResult.put("flag", "success");
mapResult.put("msg", "导入成功");
} catch (Exception e) {
e.printStackTrace();
mapResult.put("flag", "error");
mapResult.put("msg", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return mapResult;
}