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

比如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. 调试技巧 ------ printf 的使用技巧

    编译器宏:__FUNCTION__,__FILE__,__LINE__ #define __debug #ifdef __debug //#define debug(format,...) print ...

  2. zabbix监控的基础概念、工作原理及架构(一)

    zabbix监控的基础概念.工作原理及架构 转载于网络 一.什么是zabbix及优缺点 Zabbix能监视各种网络参数,保证服务器系统的安全运营,并提供灵活的通知机制以让系统管理员快速定位/解决存在的 ...

  3. 使用tushare的pandas进行to_sql操作时的No module named 'MySQLdb'错误处理

    先写在前面,用tushare获取财经类数据时,完全没有必要用python3版本 py2功能没差别,但是py3有很多地方需要修改参数才能成功运行,无端造成时间的浪费 下面进入正题,这个问题困扰了我一个下 ...

  4. .net 里面打不出来ConfigurationManager

    ConfigurationManager 这个东东是读取配置文件时需要的. 首先要引用命名空间里面 using System.Configuration; 其次呢,在解决方案的引用里,单机右键进行添加

  5. 数据结构(三)串---KMP模式匹配算法之获取next数组

    (一)获取模式串T的next数组值 1.回顾 我们所知道的KMP算法next数组的作用 next[j]表示当前模式串T的j下标对目标串S的i值失配时,我们应该使用模式串的下标为next[j]接着去和目 ...

  6. bzoj千题计划194:bzoj2115: [Wc2011] Xor

    http://www.lydsy.com/JudgeOnline/problem.php?id=2115 边和点可以重复经过,那最后的路径一定是从1到n的一条路径加上许多环 dfs出任意一条路径的异或 ...

  7. 在 Linux 中安装 VMware Tools

    由于较新的Linux版本中都包含了vm的部分组件,导致直接安装VMware Tools失败.所以这里写了篇新的. 软件版本:VMware 12 Linux版本:Ubuntu Desktop 16.04 ...

  8. 转载一篇介绍CUDA

    鉴于自己的毕设需要使用GPU CUDA这项技术,想找一本入门的教材,选择了Jason Sanders等所著的书<CUDA By Example an Introduction to Genera ...

  9. SVM Kernel Functions

    ==================================================================== This article came from here. Th ...

  10. Spring中构造器、init-method、@PostConstruct、afterPropertiesSet孰先孰后,自动注入发生时间以及单例多例的区别、SSH线程安全问题

    首先明白,spring的IOC功能需要是利用反射原理,反射获取类的无参构造方法创建对象,如果一个类没有无参的构造方法spring是不会创建对象的.在这里需要提醒一下,如果我们在class中没有显示的声 ...