org.anyline.net.HttpBuilder.init().setUrl("http://127.0.0.1/up") //上传地址 .addParam("token","abc") //其他参数 .addUploadFiles("file", new File("d:\\logo.png")) //上传文件 .addUploadFiles("file", FileUtil.file2byte(new File("d:\\logo.png"))) //上传byte数组 .build() .upload(); 或者 Map<String,Object> params = new HashMap<>();//其他参数 params.put("type", "1"); Map<String, Object> files = new HashMap<>();//上传文件 files.put("pic1", new File("d:\\logo.png"));//File files.put("pic2", FileUtil.file2byte(new File("d:\\logo.png"))); //byte[] HttpUtil.upload(url, files, params);
接收文件
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @RequestMapping(value = "/up") @ResponseBody public String upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) { }
/** * 接收多个文件 */ @RequestMapping(value = "/ups") public String uploads(HttpServletRequest request, HttpServletResponse response) { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); // 判断 request 是否有文件上传,即多部分请求 if (multipartResolver.isMultipart(request)) { // 转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 取得request中的所有文件名 Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 取得上传文件 MultipartFile file = multiRequest.getFile(iter.next()); } } }