前端代码示例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://127.0.0.1:8093/eos/api/test/gotojsp.do" method="post" enctype="multipart/form-data"> <select> <option value="0">请选择</option> <option value="1">店铺数据</option> <option value="2">产品数据</option> </select> <input type="file" name="uploadFile" /> <button type="submit">提交</button> </form> </body> </html>
Spring 中需要增加如下配置, 否则报错org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>5120000</value> </property> <property name="maxInMemorySize"> <value>1024</value> </property> </bean>
后端代码示例
//亲测 如下代码可以运行成功
@RequestMapping(value = "/gotojsp",method = RequestMethod.POST) public String gotojsp(HttpServletRequest request) { MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); MultipartHttpServletRequest params = resolver.resolveMultipart(request); System.out.println("enter");
// 如果使用下面的方式怎会报错转换失败 不要问我为什么,我只是一个搬运工 // MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request); MultipartFile file = ((MultipartHttpServletRequest) request).getFile("uploadFile"); if (file == null) { System.out.println("file is empty"); return "file is empty"; } List<List<String>> list = ExcelUtil.getExcelData(file); System.out.println("list==" + JSON.toJSONString(list)); // request.setAttribute("testSetAttribute", me.getName()); return "/test/testgogo.jsp"; }