springMVC MultipartFile file文件上传及参数接受

springMvc文件上传,首先两个基础,1。form表单属性中加上enctype="multipart/form-data"

强调:form表单的<form method="post" ...,method必须有,我这里是用的是post,至于get行不行没试过,没有method="post"也会报不是multipart请求的错误。

2。配置文件中配置MultipartResolver

文件超出限制会在进入controller前抛出异常,在允许范围内这个配置无影响

3。简单的接收方法,思路:MultipartFile 接受文件并通过IO二进制流(MultipartFile.getInputStream())输入到FileOutStream保存文件,然后该干嘛就干嘛

参数接收同MultipartFile 接收一样。

@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转成二进制流并输入到FileOutStream
    fos.close();
    //......
}

其他方法,将HttpServletRequest req强转成MultipartHttpServletRequest req后,req.getParameter("id");

HttpServletRequest request;

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
String id = multipartRequest.getParameter("id");
String fileName = file.getOriginalFilename();
//.........
经验分享 程序员 微信小程序 职场和发展