前提条件
注意:bean的id名不能改变
前台页面upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>Document
后台Controller代码
//这种是使用传统的form表单提交的,即在前台页面上点击‘上传’按钮上传文件的形式, //而且在form标签上必须指定enctype="multipart/form-data" @RequestMapping(value = "getParamFromFile",method = RequestMethod.POST) @ResponseBody public MapgetParamFromFile(@RequestParam("uploadFile") MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) { Map paramMap = new LinkedHashMap (); FileInputStream inputStream = null; try{ String filename = uploadFile.getName(); String originalFilename = uploadFile.getOriginalFilename(); System.out.println("FileName = " + filename); System.out.println("originalFilename = " + originalFilename); inputStream = (FileInputStream) uploadFile.getInputStream(); } catch (IOException e1) { paramMap.put("message", "上传文件错误"); return paramMap; } //String filePath = "E:\\work\\svn\\openeap\\code\\openeap\\src\\main\\webapp\\template\\北京市房屋租赁合同5.xml"; //paramMap = ImportFile.getParamFromFile(filePath); paramMap = ImportFile.getParamFromStream(inputStream); Iterator it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); System.out.println("参数 Key: " + e.getKey() + "; 参数 Value: " + e.getValue()); } System.out.println("生成的json为: " + JsonMapper.getInstance().toJson(paramMap)); return paramMap; } //jQuery form插件的使用 后台 @RequestMapping(value = "getParamFromFileForAjax",method = RequestMethod.POST) @ResponseBody public Map getParamFromFileForAjax(HttpServletRequest request,String fileName) { Map paramMap = new LinkedHashMap (); FileInputStream inputStream = null; //把Request强转成多部件请求对象 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; //根据文件名称获取文件对象 CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile(fileName); try{ String filename = commonsMultipartFile.getName(); String originalFilename = commonsMultipartFile.getOriginalFilename(); System.out.println("FileName = " + filename); System.out.println("originalFilename = " + originalFilename); inputStream = (FileInputStream) commonsMultipartFile.getInputStream(); } catch (IOException e1) { paramMap.put("message", "上传文件错误"); return paramMap; } //String filePath = "E:\\work\\svn\\openeap\\code\\openeap\\src\\main\\webapp\\template\\北京市房屋租赁合同5.xml"; //paramMap = ImportFile.getParamFromFile(filePath); paramMap = ImportFile.getParamFromStream(inputStream); Iterator it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); System.out.println("参数 Key: " + e.getKey() + "; 参数 Value: " + e.getValue()); } System.out.println("生成的json为: " + JsonMapper.getInstance().toJson(paramMap)); return paramMap; }
异步上传文件有两种方式:
参考的文章:
http://www.cnblogs.com/zhuxiaojie/p/4783939.html#autoid-1-0-0