java中远程http文件上传及file2multipartfile
工作中有时会遇到各种需求,你得变着法儿去解决,当然重要的是在什么场景中去完成。
比如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的更多相关文章
- Java FtpClient 实现文件上传服务
一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...
- Java中实现文件上传下载的三种解决方案
第一点:Java代码实现文件上传 FormFile file=manform.getFile(); String newfileName = null; String newpathname=null ...
- 【原创】用JAVA实现大文件上传及显示进度信息
用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/grayprince/UploadBigFil ...
- Java下载https文件上传到阿里云oss服务器
Java下载https文件上传到阿里云oss服务器 今天做了一个从Https链接中下载音频并且上传到OSS服务器,记录一下希望大家也少走弯路. 一共两个类: 1 .实现自己的证书信任管理器类 /** ...
- 【Java】JavaWeb文件上传和下载
文件上传和下载在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件 ...
- java+web+大文件上传下载
文件上传是最古老的互联网操作之一,20多年来几乎没有怎么变化,还是操作麻烦.缺乏交互.用户体验差. 一.前端代码 英国程序员Remy Sharp总结了这些新的接口 ,本文在他的基础之上,讨论在前端采用 ...
- Java开发系列-文件上传
概述 Java开发中文件上传的方式有很多,常见的有servlet3.0.common-fileUpload.框架.不管哪种方式,对于文件上传的本质是不变的. 文件上传的准备 文件上传需要客户端跟服务都 ...
- Ceph RGW服务 使用s3 java sdk 分片文件上传API 报‘SignatureDoesNotMatch’ 异常的定位及规避方案
import java.io.File; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.profile ...
- Java开发之文件上传
文件上传有SmartUpload.Apache的Commons fileupload.我们今天介绍Commons fileupload的用法. 1.commons-fileupload-1.3.1.j ...
随机推荐
- Linux常用命令history/tcpdump/awk/grep
1. 历史命令回显history 查询是什么时间什么人操作过文件: echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> ...
- python的面向对象-类的数据属性和实例的数据属性相结合-无命名看你懵逼不懵逼系列
1. class Chinese: country='China' def __init__(self,name): self.name=name def play_ball(self,ball): ...
- python爬虫 scrapy3_ 安装指南
安装指南 安装Scrapy 注解 请先阅读 平台安装指南. 下列的安装步骤假定您已经安装好下列程序: Python 2.7 Python Package: pip and setuptools. ...
- c#的委托用法delegate
- 接口测试Case之面向页面对象编写规范
一.什么是页面对象化 主要提倡的思想是:万物皆对象,即把一个Page看成一个对象,来进行接口自动化Case的编写,不要闲扯,直接讲怎么个操作法呢? 二.有什么优势? 2.1 Case层次清晰,便于管理 ...
- JMS学习(四)-一个简单的聊天应用程序分析
一,介绍 本文介绍一个简单的聊天应用程序:生产者将消息发送到Topic上,然后由ActiveMQ将该消息Push给订阅了该Topic的消费者.示例程序来自于<JAVA 消息服务--第二版 Mar ...
- CF232C Doe Graphs
传送门 Solution: (不理解时对着图研究一下就清楚啦!!!) sm[i]为|D(i)| (x,y,n)为x,y在D(n)中的最短路 已知sm[i-1]+1为D(i)的割点 于是x-y的最短 ...
- python3之Splash
Splash是一个javascript渲染服务.它是一个带有HTTP API的轻量级Web浏览器,使用Twisted和QT5在Python 3中实现.QT反应器用于使服务完全异步,允许通过QT主循环利 ...
- 【最简单的方法】js判断字符串是否为JSON格式(20180115更新)
前言 针对 “js判断字符串是否为JSON格式” 这个问题,在网上查了许多资料,都没找到自己想要的答案. 但是看到这个帖子<js判断字符串是否为JSON格式>后,突然灵光一闪,想到一种很简 ...
- BCTF2017 BabyUse
BCTF2017 BabyUse 问题 问题在于drop函数中在释放块之后没有清空bss_gun_list中的指针. 一般因为存在对bss_gun_flag的验证,所以不会出现什么问题,但是在use功 ...