前台代码
<html>
<head>
<title>Title</title>
</head>
<script>
function a() {
var formData = new FormData();
var files = $("#files")[0].files[0];
formData.append("files",files);
$.post({
url:"/addMoreUserAction",
data:formData,
cache: false,
processData: false,
contentType: false,
success:function (data) {
console.log(data)
var datas = JSON.parse(data);
console.log(datas)
alert(datas.retMsg)
}
})
}
</script>
<body>
<input type="file" id="files" formenctype="multipart/form-data">
<input type="button" id="upload" onclick="a()" value="点击导入">
</body>
</html>
**
后台代码
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
Map<String,String>map = new HashMap<>();
try {
List<FileItem> items = upload.parseRequest(req);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = item.getName();
int idx = fileName.lastIndexOf(".");//找到.的索引号
String path = fileName.substring(idx);//截取文件全路径
String fileNameUpload = new Date().getTime() + path;
String newPath = "C:/jar/";
File f = new File(newPath);
if (!f.exists()) {
f.mkdir();
}
try {
String fi = newPath + fileNameUpload;//文件的新路径
item.write(new File(fi));
List<String> list = getDataFromFile(fi);
userService userService = new userService();
map = userService.addMoreUser(list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
String json = JSON.toJSONString(map);
System.out.println(json);
resp.getWriter().println(json);
}
/**
* 读文件数据并保存至数组中
*/
private List getDataFromFile(String path) {
File file = new File(path);//得到输出流
List<String> list = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));//设置文件格式为GBK,不然中文可能乱码
StringBuffer sb = new StringBuffer();
String s = "";
while ((s = bufferedReader.readLine()) != null) {//读取每行值存入list
list.add(s);
sb.append(s + "\n");
System.out.println(s);
}
bufferedReader.close();
String str = sb.toString();
System.out.println(str);
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
**