springMvc文件上传,首先两个基础,前端
1.form表单属性中加上enctype="multipart/form-data"spring
强调:form表单的<form method="post" ...,method必须有,我这里是用的是post,至于get行不行没试过,没有method="post"也会报不是multipart请求的错误。后端
2.配置文件中配置MultipartResolverapp
文件超出限制会在进入controller前抛出异常,在容许范围内这个配置无影响post
3.后端controller层参数接收测试
简单的接收方法,思路:MultipartFile 接受文件并经过IO二进制流(MultipartFile.getInputStream())输入到FileOutStream保存文件,而后该干吗就干吗编码
参数接收同MultipartFile 接收同样。spa
接受form表单截图中name为file和id的文件和参数。以下.net
@RequestMapping(value = "attendee_uploadExcel.do") @ResponseBody public void uploadExcel(@RequestParam("file") MultipartFile file, @RequestParam("id") String id) throws Exception { //form表单提交的参数测试为String类型 if (file == null) return ; String fileName = file.getOriginalFilename(); String path = getRequest().getServletContext().getRealPath("/upload/excel"); //获取指定文件或文件夹在工程中真实路径,getRequest()这个方法是返回一个HttpServletRequest,封装这个方法为了处理编码问题 FileOutputStream fos = FileUtils.openOutputStream(new File(path+"/" +fileName));//打开FileOutStrean流 IOUtils.copy(file.getInputStream(),fos);//将MultipartFile file转成二进制流并输入到FileOutStrean fos.close();// ...... }
2、先后端分享的文件上件方法,此时前端传后后台的为文件base64编码的字符串excel
其余方法,将HttpServletRequest req强转成MultipartHttpServletRequest req后,req.getParameter("id");
@ResponseBody @PostMapping("/import") public Integer importFromExcel(HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); // 经过参数名获取指定文件 String id = multipartRequest.getParameter("id"); String fileName = file.getOriginalFilename(); ......... }
原文连接 http://blog.csdn.net/u013771277/article/details/47384817