工作中有时会遇到各种需求,你得变着法儿去解决,当然重要的是在什么场景中去完成。

比如Strut2中file类型如何转换成multipartfile类型,找了几天,发现一个变通的方法记录如下(虽然最后没有用上。。):

 private static MultipartFile getMulFileByPath(String picPath) {  

         FileItem fileItem = createFileItem(picPath);  

         MultipartFile mfile = new CommonsMultipartFile(fileItem);  

         return mfile;  

     }  

 private static FileItem createFileItem(String filePath)  

     {  

         FileItemFactory factory = new DiskFileItemFactory(16, null);  

         String textFieldName = "textField";  

         int num = filePath.lastIndexOf(".");  

         String extFile = filePath.substring(num);  

         FileItem item = factory.createItem(textFieldName, "text/plain", true,  

             "MyFileName" + extFile);  

         File newfile = new File(filePath);  

         int bytesRead = 0;  

         byte[] buffer = new byte[4096];  

         try  

         {  

             FileInputStream fis = new FileInputStream(newfile);  

             OutputStream os = item.getOutputStream();  

             while ((bytesRead = fis.read(buffer, 0, 8192))  

                 != -1)  

             {  

                 os.write(buffer, 0, bytesRead);  

             }  

             os.close();  

             fis.close();  

         }  

         catch (IOException e)  

         {  

             e.printStackTrace();  

         }  

         return item;  

     }  

file2multipartfile

好不容易写好了一个完整的远程上传方法,并且本地测试已经通过能用,提交后发现有个类实例化不了,debug发现是包不兼容问题(尴尬),

但是以前别人用过的东西,你又不能升级,主要是没权限,不得不去低级的版本中找变通的类似方法,即便方法已经过时了。。

//httpclient(4.5.3)远程传输文件工具类

 public static Map<String, String> executeDriverServer(String driverUrl, Map<String, Object> param,String multipart, String contentType,int timeout,String picPath) throws Exception {

         String res = ""; // 请求返回默认的支持json串

         Map<String, String> map = new HashMap<String, String>();
ContentType ctype = ContentType.create("content-disposition","UTF-8"); Map<String, String> map = new HashMap<String, String>(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); String res = ""; // 请求返回默认的支持json串 HttpResponse httpResponse = null; try { HttpPost httpPost = new HttpPost(driverUrl); //设置请求和传输超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(5000).build(); httpPost.setConfig(requestConfig); // BTW 4.3版本不设置超时的话,一旦服务器没有响应,等待时间N久(>24小时)。 if(httpPost!=null){ if("formdata".equals(multipart)){ MultipartEntityBuilder mentity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); Set<String> keyset = param.keySet(); for (String key : keyset) { Object paramObj = Validate.notNull(param.get(key)); if(paramObj instanceof MultipartFile) { mentity.addBinaryBody(key, ((MultipartFile) paramObj).getInputStream(),ctype,((MultipartFile) paramObj).getOriginalFilename()); }else if(paramObj instanceof File){ mentity.addBinaryBody(key, (File)paramObj);//(key, new FileInputStream((File)paramObj),ctype,((File)paramObj).getName()); }else{ mentity.addPart(key,new StringBody(paramObj.toString(),ctype)); //mentity.addTextBody(key,paramObj.toString()); } logger.info("key::::"+key); logger.info("paramObj::::"+paramObj.toString()); } HttpEntity entity = mentity.build(); HttpUriRequest post = RequestBuilder.post().setUri(driverUrl).setEntity(entity).build(); httpResponse = closeableHttpClient.execute(post); }else { HttpEntity entity = convertParam(param, contentType); httpPost.setEntity(entity); httpResponse = closeableHttpClient.execute(httpPost); } if(httpResponse == null) { throw new Exception("无返回结果"); } // 获取返回的状态码 int status = httpResponse.getStatusLine().getStatusCode(); logger.info("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",状态="+status); if(status == HttpStatus.SC_OK){ HttpEntity entity2 = httpResponse.getEntity(); InputStream ins = entity2.getContent(); res = toString(ins); ins.close(); }else{ InputStream fis = httpResponse.getEntity().getContent(); Scanner sc = new Scanner(fis); logger.info("Scanner:::::"+sc.next()); logger.error("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",错误Code:"+status); } map.put("code", String.valueOf(status)); map.put("result", res); logger.info("执行Post方法请求返回的结果 = " + res); } } catch (ClientProtocolException e) { map.put("code", HttpClientUtil.CLIENT_PROTOCOL_EXCEPTION_STATUS); map.put("result", e.getMessage()); } catch (UnsupportedEncodingException e) { map.put("code", HttpClientUtil.UNSUPPORTED_ENCODING_EXCEPTION_STATUS); map.put("result", e.getMessage()); } catch (IOException e) { map.put("code", HttpClientUtil.IO_EXCEPTION_STATUS); map.put("result", e.getMessage()); } finally { try { closeableHttpClient.close(); } catch (IOException e) { logger.error("调用httpClient出错", e); throw new Exception("调用httpClient出错", e); } } private static String toString(InputStream in) throws IOException{ ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len; while((len = in.read(b)) != -1) { os.write(b, 0, len); } return os.toString("UTF-8"); }
}

4.53包下http远程文件上传

//httpclient(4.2.2)老版本远程传输文件工具类

 public static Map<String, String> executeDriverServer(String driverUrl, Map<String, Object> param,String multipart, String contentType,int timeout,String picPath) throws Exception {

         String res = ""; // 请求返回默认的支持json串

         Map<String, String> map = new HashMap<String, String>();

         ContentType ctype = ContentType.create("content-disposition","UTF-8");

         HttpPost httpPost = new HttpPost(driverUrl);

         MultipartEntity reqEntity = new MultipartEntity();

         Set<String> keyset = param.keySet();

         File tempFile = new File(picPath);

         for (String key : keyset) {

             Object paramObj = Validate.notNull(param.get(key));

             if(paramObj instanceof File) {

                 FileBody fileBody = new FileBody(tempFile);

                 reqEntity.addPart(key, fileBody);

             }else{

                 reqEntity.addPart(key,new StringBody(paramObj.toString()));

             }

             logger.info("key::::"+key);

             logger.info("paramObj::::"+paramObj.toString());

         }

         httpPost.setEntity(reqEntity);

         HttpClient httpClient = new DefaultHttpClient();

         HttpResponse httpResponse = httpClient.execute(httpPost);

         // 获取返回的状态码

         int status = httpResponse.getStatusLine().getStatusCode();

         logger.info("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",状态="+status);

         if(status == HttpStatus.SC_OK){

             HttpEntity entity2 = httpResponse.getEntity();

             InputStream ins = entity2.getContent();

             res = toString(ins);

             ins.close();

         }else{

             InputStream fis = httpResponse.getEntity().getContent();

             Scanner sc = new Scanner(fis);

             logger.info("Scanner:::::"+sc.next());

             logger.error("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",错误Code:"+status);

         }

         map.put("code", String.valueOf(status));

         map.put("result", res);

         logger.info("执行Post方法请求返回的结果 = " + res);

         return map;

     }

4.2.2版本http远程传输文件工具类

希望对大家有点帮助!平常心。

java中远程http文件上传及file2multipartfile的更多相关文章

  1. Java FtpClient 实现文件上传服务

    一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...

  2. Java中实现文件上传下载的三种解决方案

    第一点:Java代码实现文件上传 FormFile file=manform.getFile(); String newfileName = null; String newpathname=null ...

  3. 【原创】用JAVA实现大文件上传及显示进度信息

    用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/grayprince/UploadBigFil ...

  4. Java下载https文件上传到阿里云oss服务器

    Java下载https文件上传到阿里云oss服务器 今天做了一个从Https链接中下载音频并且上传到OSS服务器,记录一下希望大家也少走弯路. 一共两个类: 1 .实现自己的证书信任管理器类 /** ...

  5. 【Java】JavaWeb文件上传和下载

    文件上传和下载在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件 ...

  6. java+web+大文件上传下载

    文件上传是最古老的互联网操作之一,20多年来几乎没有怎么变化,还是操作麻烦.缺乏交互.用户体验差. 一.前端代码 英国程序员Remy Sharp总结了这些新的接口 ,本文在他的基础之上,讨论在前端采用 ...

  7. Java开发系列-文件上传

    概述 Java开发中文件上传的方式有很多,常见的有servlet3.0.common-fileUpload.框架.不管哪种方式,对于文件上传的本质是不变的. 文件上传的准备 文件上传需要客户端跟服务都 ...

  8. Ceph RGW服务 使用s3 java sdk 分片文件上传API 报‘SignatureDoesNotMatch’ 异常的定位及规避方案

    import java.io.File;   import com.amazonaws.AmazonClientException; import com.amazonaws.auth.profile ...

  9. Java开发之文件上传

    文件上传有SmartUpload.Apache的Commons fileupload.我们今天介绍Commons fileupload的用法. 1.commons-fileupload-1.3.1.j ...

随机推荐

  1. Excel:公式应用技巧汇总

    1.合并单元格添加序号:=MAX(A$1:A1)+1 不重复的个数: 公式1:{=SUM(1/COUNTIF(A2:A8,A2:A8))} 公式2:{=SUM(--(MATCH(A2:A8,A2:A8 ...

  2. POJ 3252 Round Number(数位DP)

    Round Numbers Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 6983   Accepted: 2384 Des ...

  3. Dubbo学习笔记6:Dubbo增强SPI与SPI中扩展点自动包装的实现原理

    在Dubbo整体架构分析中介绍了Dubbo中除了Service和Config层为API外,其他各层均为SPI,为SPI意味着下面各层都是组件化可以被替换的,也就是扩展性比较强,这也是Dubbo比较好的 ...

  4. bzoj千题计划253:bzoj2154: Crash的数字表格

    http://www.lydsy.com/JudgeOnline/problem.php?id=2154 #include<cstdio> #include<algorithm> ...

  5. HDU 1729 类NIM 求SG

    每次有n个盒子,每个盒子有容量上限,每次操作可以放入石头,数量为不超过当前盒子中数量的平方,不能操作者输. 一个盒子算一个子游戏. 对于一个盒子其容量为s,当前石子数为x,那么如果有a满足 $a \t ...

  6. Java迭代器用法

    public class Test01 { public static void main(String[] args) { List list = new ArrayList(); list.add ...

  7. shell 检测安装包

    检测 wget 是否存在 rpm -q wget >/dev/null ];then echo "install wget,Please wait..." yum -y in ...

  8. 第13月第13天 iOS 放大消失动画

    1. - (void) animate { [UIView animateWithDuration:0.9 animations:^{ CGAffineTransform transform = CG ...

  9. 五大常见的MySQL高可用方案【转】

    1. 概述 我们在考虑MySQL数据库的高可用的架构时,主要要考虑如下几方面: 如果数据库发生了宕机或者意外中断等故障,能尽快恢复数据库的可用性,尽可能的减少停机时间,保证业务不会因为数据库的故障而中 ...

  10. VMware下centos桥接模式静态ip配置

    声明:本文转载自http://blog.csdn.net/ltr15036900300/article/details/48828207,非原创. 一.配置虚拟机centos网络 备份网络文件 [ro ...