采用HttpClient3.x上传文件 spring 文件上传
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了采用HttpClient3.x上传文件 spring 文件上传相关的知识,希望对你有一定的参考价值。
最近,项目需要调用第三方的系统上传图片,在长传图片的同时,还需要携带其他的请求参数;整体的流程是:网页----》spring mvc---》业务处理----》调用第三方系统上传图片;
在此期间遇到的问题是:在调用第三方系统上传图片时,除了图片文件参数外,其他参数期望通过request.getParameter()方法能够访问到,采用了很多方式,都不行,最终通过不断的尝试,测试成功,特贡献出来供需要的人员参考!
采用spring 的MultipartFile进行文件上传,代码如下
@Note(note = "bigAnt:上传文件", author = "zhangwenbo") @RequestMapping("midifyPicture") @ResponseBody public SimpleMessage<Object> modifyPicture(@RequestParam("file") MultipartFile file, HttpServletRequest req) { logger.info("modifyHeaderPicture has invoked.filename is " + file.getOriginalFilename()); SimpleMessage<Object> sm = new SimpleMessage<Object>(); int index = file.getOriginalFilename().lastIndexOf("."); String imageSupportType = SpiConfig.getPropValue("IMAGE_SUPPORT_TYPE"); if (imageSupportType.indexOf("," + file.getOriginalFilename().substring(index + 1) + ",") < 0) { sm.set("message", "file type is error.the support type is " + imageSupportType.substring(1, imageSupportType.length() - 1)); logger.info("the file type is error.the req file type is " + file.getOriginalFilename().substring(index + 1)); return sm; } File fileIO = null; try { fileIO = File.createTempFile(file.getOriginalFilename().substring(0, index), file.getOriginalFilename().substring(index + 1)); if (!fileIO.exists()) { fileIO.createNewFile(); } file.transferTo(fileIO); } catch (IOException e) { logger.warn("transferto file fail.", e); } Map<String, Object> postBody = new HashMap<String, Object>(); postBody.put("loginname", req.getSession().getAttribute(BigAntHelper.SESSION_USER_ID)); BigAntBaseRes uploadResult = BigAntClient.getInstance().uploadPicture(postBody, file.getOriginalFilename(), fileIO); logger.info("upload return msg is " + uploadResult); if (null != uploadResult) { if ("1".equals(uploadResult.getStatus().trim())) { sm.set("data", uploadResult.getData()); } else { sm.set("message", uploadResult.getMsg()); } } else { sm.set("message", "upload fail"); } return sm; } |
2.采用HTTPCLIENT3.x上传文件,代码如下
/** * 长传文件<br/> * @param postBody * @param filename * @param file * @return */ public BigAntBaseRes uploadPicture(Map<String,Object> postBody,String filename,File file){ logger.info("upload file"); postBody.put("token",SpiConfig.getPropValue("BIGANT_BASE_TOKEN")); postBody.put("op", "uploadAvater"); return UploadFileClient.uploadFile(BigAntHelper.getUploadUrl(), postBody, filename, file,BigAntBaseRes.class); } /** * 长传文件<br/> * * @param url * 目标服务的url<br/> * @param reqParams * 请求参数<br/> * @param filename * 需要上传的文件名称<br/> * @param file * 需要上传的文件<br/> * @return */ public static <T> T uploadFile(String url, Map<String, Object> reqParams, String filename, File file, Class<T> returnClass) { HttpClient client = new HttpClient(); logger.info("URL:" + url + " and the filename is " + filename); HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams(); managerParams.setConnectionTimeout(10000); PostMethod post = new PostMethod(url); HttpMethodParams params = post.getParams(); params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); params.setContentCharset("UTF-8"); // 设置消息体 List<Part> requestPart = new ArrayList<Part>(); if (null != reqParams && reqParams.size() > 0) { Iterator<String> it = reqParams.keySet().iterator(); while (it.hasNext()) { String key = it.next(); if (null != reqParams.get(key)) { try { requestPart.add(new StringPart(key, URLEncoder.encode(reqParams.get(key).toString(), "UTF-8"))); logger.info("key:" + key + " and value is :" + URLEncoder.encode(reqParams.get(key).toString(), "UTF-8")); } catch (Exception e) { logger.warn("parse the send msg fail.", e); } } } } try { // 设置文件内容 requestPart.add(new FilePart(filename, file)); post.setRequestEntity(new MultipartRequestEntity(requestPart.toArray(new Part[1]), post.getParams())); int status = client.executeMethod(post); String result = post.getResponseBodyAsString(); if (status == HttpStatus.SC_OK) { logger.info("return result of uploading file is " + result); } else { if (null != result) { result = "upload fail"; } logger.warn("upload file fail."); } Gson gson = new Gson(); T returnResult = gson.fromJson(result, returnClass); return returnResult; } catch (Exception e) { e.printStackTrace(); logger.warn("upload file fail.the filename is " + filename, e); } finally { if (null != post) { post.releaseConnection(); } } return null; } |
本文出自 “java” 博客,请务必保留此出处http://zwbjava.blog.51cto.com/2789897/1787016
以上是关于采用HttpClient3.x上传文件 spring 文件上传的主要内容,如果未能解决你的问题,请参考以下文章
spring boot MultipartFile[]文件上传
spring boot MultipartFile[]文件上传
上传文件限制导致413-Request Entity Too Large