1 后台
(1)java
@RequestMapping(value = "/showapi", method = RequestMethod.POST) public ResponseEntity showapi(@RequestParam("file") MultipartFile multipartFile) { byte[] byteImg = multipartFile.getBytes(); } 普通的接口,只不过接收参数类型为MultipartFile(2)spring配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000" /> <property name="maxInMemorySize" value="100000" /> </bean> dispatcherServlet是没有处理multipart/form-data,需要单独配置一个resolver,id="multipartResolver"默认如此设置 (3)maven依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> <!-- makesure correct version here --> </dependency> 2 客户端 public static String decaptcha(File file) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(ReadProperties.read("captcha.url")); RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(20000).build(); post.setConfig(config); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", fileBody); // 相当于 <input type="file" class="file" name="file">,匹配@RequestParam("file") // .addPart()可以设置模拟浏览器<input/>的表单提交 HttpEntity entity = builder.build(); post.setEntity(entity); String result = ""; try { CloseableHttpResponse e = client.execute(post); HttpEntity resEntity = e.getEntity(); if(entity != null) { result = EntityUtils.toString(resEntity); System.out.println("response content:" + result); } } catch (IOException var10) { logger.error("请求解析验证码io异常",var10); var10.printStackTrace(); } return result; }
附录(浏览器请求数据格式):
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="firstName"Charles
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="lastName"Xavier
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="email"charles@xmen.com
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="username"professorx
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="password"letmein01
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="profilePicture"; filename="me.jpg"Content-Type: image/jpeg
[[ Binary image data goes here ]]
------WebKitFormBoundaryqgkaBn8IHJCuNmiW--
这些name就是映射到@RequestParam(name)