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 ...
随机推荐
- debian8.4 ubuntu14.04双系统_debian8.4硬盘安装
本文根据官网说明和实际安装而写,利在分享知识,但转载请注明出处以尊重知识! 一 首先在win7下利用EasyBCD添加安装选项,“添加新条目|安装|配置” 在弹出的memu.lst中填写如下内容: t ...
- map文件的使用
map文件相信大家并不陌生,大家都知道是用来调试的,但是具体怎么用你又清不清楚呢? 其实也很简单 1.拿JQ为例,我们需要备有jquery.js.jquery.min.js.jquery.min.ma ...
- 网络报错:“The connection is not for this device.”
网络报错:“The connection is not for this device.” 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 记得在前几天工作的时候,有一个同时通过微信 ...
- 基础知识点 关于 prototype __proto__
基础知识点 关于 prototype __proto__ 供js新手参考 JavaScript 的一些基础知识点: 在 JavaScript 中,所有对象 o 都拥有一个隐藏的原型对象(在 Fire ...
- git的权威指南
CHENYILONG 博客 git的权威指南 全屏 © chenyilong.本站由Postach.io 博客
- win8开wifi共享无法使用的问题解决办法
相信现在不少人都安装了windows8操作系统,因为windows8这个全新的操作系统用起来 确实挺强大,包括漂亮的开始屏,但是不得不说这个系统的兼容性还是有待提高,所以win8我的 装了又卸,卸了又 ...
- ListUtil(差集、交集、并集)
package cn.fraudmetrix.octopus.horai.biz.utils; import java.util.ArrayList; import java.util.Arrays; ...
- Useful Online Resources for New Hackers
出处:https://www.hackerone.com/blog/resources-for-new-hackers HackerOne喜欢花时间与活跃的黑客和有兴趣学习如何破解的人交谈. 就在上周 ...
- Coins in a Line I & II
Coins in a Line I There are n coins in a line. Two players take turns to take one or two coins from ...
- win10 安装IIS说明操作
1.点左下角的Windows,所有应用,找到Windows系统,打开控制面板. 2.进入控制面板之后点击程序,可能你的控制面板和图片里的不太一样,不过没关系,找到程序两个字点进去就行. 3.接下来,在 ...