HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>upload</title> </head> <body> <form id="pForm" enctype="multipart/form-data"> <input name="file" type="file" id="theFile"/> </form> </body> </html>
js
/*只是核心代码*/ function upLoadFile() { $("#theFile").change(function () { var filePath = $(this).val(); if (!filePath.endsWith(".txt")){ alert("请上传txt格式的文件"); return false; } //确定上传 var form = new FormData(document.getElementById("pForm")); $.ajax({ url:fileImport.do, type:'POST', data:form, async:true, processData:false, contentType:false, scriptCharset:'utf-8', success:function (data) { var flag = data["data0"]; if (flag){ alert("文件上传成功!"); }else{ alert("文件上传失败!"); } } }); }); }
Java后台
@Controller public class UpLoad { public String fileImport(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response){ //获取文件件进行保存 File fileDir = new File("D:\\xxxxx"); if(!fileDir.exists()||!fileDir.isDirectory()){ fileDir.mkdir(); } String url = "被上传文件的全路径"; //文件上传 try { InputStream in = file.getInputStream(); File file2 = new File(url); OutputStream out = new FileOutputStream(file2); byte[] b = new byte[1024]; int len = 0; while((len = in.read(b))!=-1){ out.write(b,0,len); } in.close(); out.close(); //读取每行内容 FileInputStream fis = new FileInputStream(file2); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String str = null; while ((str = br.readLine())!=null){ System.out.println(str); } br.close(); isr.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return null; } }
当然,需要先将commons相关jar包引入到项目中