Java实现上传txt,doc,docx⽂件并且读取内容
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.sponse);
$("#resumeList").datagrid();
layer.alert(info1.msg);
//console.ssage);
},
Error: function(up,info, err) { //上传出错的时候触发
layer.ssage);
}
}
});
uploaderXls.init();
2,后台接收⽂件,并读取:
MultipartFile是spring的⼀个接⼝,通常我们可以在controller定义⽅法使⽤MultipartFile接收form表单提交的⽂件,然后将MultipartFile可以转化成⼀个⽂件。
可以直接通过MultipartFile⾃带的getInputStream()⽅法将它转换成File
1 @RequestMapping(params = "importExcel", method = RequestMethod.POST)
2 @ResponseBody
3public 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 (OriginalFilename().endsWith(".doc")) {
java创建文件13      WordExtractor ex = new InputStream());
14      buffer = ex.getText();
15      ex.close();
16
17      } else if (OriginalFilename().endsWith(".docx")) {
18      XWPFDocument xdoc = new InputStream());
19      XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
20      buffer = Text();
21      extractor.close();
22
23      } else if (OriginalFilename().endsWith(".txt")) {
24      InputStreamReader read = new InputStreamReader(
25      (InputStream()),"UTF-8");
26      BufferedReader bufferedReader = new BufferedReader(read);
27      String readerStr = null;
28      while((readerStr = adLine()) != null){
29        buffer = buffer + "\n" +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);
42return j;
43 }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。