1,前端上传/导入文件:
var uploaderXls = new plupload.Uploader({//创建实例的构造方法 runtimes: 'gears,html5,html4,silverlight,flash', //上传插件初始化选用那种方式的优先级顺序 browse_button: 'btnImportXls', // 上传按钮 url: "resumeController.do?importExcel", //远程上传地址 flash_swf_url: 'plug-in/plupload/js/Moxie.swf', //flash文件地址 silverlight_xap_url: 'plug-in/plupload/js/Moxie.xap', //silverlight文件地址 filters: { max_file_size: '10mb', //最大上传文件大小(格式100b, 10kb, 10mb, 1gb) mime_types: [//允许文件上传类型 {title: "files", extensions: "txt,doc,docx"} ] }, multipart_params:{isup:"1"}, multi_selection: false, //true:ctrl多文件上传, false 单文件上传 init: { FilesAdded: function(up, files) { //文件上传前 debugger; uploaderXls.start(); }, FileUploaded: function(up, file, info) { //文件上传成功的时候触发 info1 = JSON.parse(info.response); $("#resumeList").datagrid(); layer.alert(info1.msg); //console.log(info.message); }, Error: function(up,info, err) { //上传出错的时候触发 layer.alert(err.message); } } }); uploaderXls.init();
2,后台接收文件,并读取:
MultipartFile是spring的一个接口,通常我们可以在controller定义方法使用MultipartFile接收form表单提交的文件,然后将MultipartFile可以转化成一个文件。
可以直接通过MultipartFile自带的getInputStream()方法将它转换成File
1 @RequestMapping(params = "importExcel", method = RequestMethod.POST) 2 @ResponseBody 3 public AjaxJson uploaderResumes(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception { 4 AjaxJson j = new AjaxJson(); 5 String message = ""; 6 // 判断文件是否为空 7 if (!file.isEmpty()) { 9 String buffer = ""; 11 try { 12 if (file.getOriginalFilename().endsWith(".doc")) { 13 WordExtractor ex = new WordExtractor(file.getInputStream()); 14 buffer = ex.getText(); 15 ex.close(); 16 17 } else if (file.getOriginalFilename().endsWith(".docx")) { 18 XWPFDocument xdoc = new XWPFDocument(file.getInputStream()); 19 XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc); 20 buffer = extractor.getText(); 21 extractor.close(); 22 23 } else if (file.getOriginalFilename().endsWith(".txt")) { 24 InputStreamReader read = new InputStreamReader( 25 (file.getInputStream()),"UTF-8"); 26 BufferedReader bufferedReader = new BufferedReader(read); 27 String readerStr = null; 28 while((readerStr = bufferedReader.readLine()) != null){ 29 buffer = buffer + " " +readerStr; 30 } 31 read.close(); 32 } else { 33 message = "格式有误,只允许txt,doc和docx"; 34 } 35 } catch (FileNotFoundException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 message = "操作失败"; 39 } 40 } 41 j.setMsg(message); 42 return j; 43 }