SpringMvc上传txt、csv并解析

末蓝、 2022-05-17 11:06 409阅读 0赞

applicationContext.xml

  1. <!-- 文件上传配置 -->
  2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  3. <!-- 请求编码格式 -->
  4. <property name="defaultEncoding" value="utf-8"></property>
  5. <!-- 上传文件大小(单位:字节) -->
  6. <property name="maxUploadSize" value="50000000"></property>
  7. <!-- 缓冲区大小(单位:KB) -->
  8. <property name="maxInMemorySize" value="10240"></property>
  9. </bean>

Controller

  1. @ResponseBody
  2. @RequestMapping(value = "addLabel", method = RequestMethod.POST)
  3. public ResponseEntity addLabel(@RequestParam(value = "files") MultipartFile files) {
  4. String sourceName = files.getOriginalFilename(); // 原始文件名
  5. String fileType = sourceName.substring(sourceName.lastIndexOf("."));
  6. if (files.isEmpty() || StringUtils.isBlank(fileType)) {
  7. return new ResponseEntity(ResponseEntity.STATUS_FAIL, null, "文件不能为空", null);
  8. }
  9. if (!".txt".equals(fileType.toLowerCase()) && !".csv".equals(fileType.toLowerCase())) {
  10. return new ResponseEntity(ResponseEntity.STATUS_FAIL, null, "文件暂时只支持txt,csv格式", null);
  11. }
  12. // 存放文件临时路径
  13. String base = request.getSession().getServletContext().getRealPath("/upload//"); //获取文件上传的路径,在webapp下的upload中
  14. File file = new File(base);
  15. if (!file.exists()) {
  16. file.mkdirs();
  17. }
  18. // 讲文件上传到临时目录
  19. String path = base + File.separator + sourceName;
  20. File upload = new File(path);
  21. try {
  22. files.transferTo(upload);
  23. } catch (IOException e) {
  24. return new ResponseEntity(ResponseEntity.STATUS_FAIL, null, "文件上传失败,请联系管理员", null);
  25. }
  26. // 解析文件
  27. BufferedReader br = null;
  28. FileReader reader = null;
  29. try {
  30. reader = new FileReader(upload);
  31. br = new BufferedReader(reader);
  32. String line = "";
  33. while ((line = br.readLine()) != null) {
  34. if (line.trim().length() == 11) {
  35. phones.add(line.trim());
  36. }
  37. }
  38. } catch (Exception e) {
  39. log.error("上传文件失败", e);
  40. return new ResponseEntity(ResponseEntity.STATUS_FAIL, null, "读取文件失败,请联系管理员", null);
  41. } finally {
  42. try {
  43. if (reader != null) {
  44. reader.close();
  45. reader = null;
  46. }
  47. if (br != null) {
  48. br.close();
  49. br = null;
  50. }
  51. } catch (Exception e) {
  52. return new ResponseEntity(ResponseEntity.STATUS_FAIL, null, "关闭流失败,请联系管理员", null);
  53. }
  54. // 删除临时文件
  55. if (upload.isFile()) {
  56. upload.delete();
  57. }
  58. }
  59. return new ResponseEntity(ResponseEntity.STATUS_OK);
  60. }

发表评论

表情:
评论列表 (有 0 条评论,409人围观)

还没有评论,来说两句吧...

相关阅读

    相关 javaexcel以及

    一、前言 在写管理后台的需求的时候,经常会用到上传excel的功能,需要我们解析Excel的内容,导入数据等。 二、上传 上传到文件服务器,文件服务有相关的上传接

    相关 Excel

    该篇博客废除,见解析excel工具类 兼容2007和2003两种类型的文件,举例:这里模板有两个页脚: ![20180404100358222][]