HttpClient上传文件
1、上传客户端代码:
public static void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://172.18.5.107:90/Download.html");
FileBody bin = new FileBody(new File("D:\\BaiduNetdiskDownload\\背景圖\\b.jpg"));
FileBody bin2 = new FileBody(new File("D:\\BaiduNetdiskDownload\\背景圖\\哈哈哈.jpg"));
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
StringBody comment = new StringBody("123哈哈哈45", contentType);
MultipartEntityBuilder builder=MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
//文件流参数
builder.addPart("bin",bin);
builder.addPart("bi哈哈n2",bin2);
//普通的参数
builder.addPart("employee_no",comment);
HttpEntity reqEntity= builder.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Response content: " + EntityUtils.toString(resEntity,"UTF-8"));
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、后台下载代码,原生servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = null;
//跨越访问
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
File directory = null;
List<FileItem> items = new ArrayList<FileItem>();
try {
items = upload.parseRequest(request);
// 得到所有的文件
Iterator<FileItem> it = items.iterator();
while (it.hasNext()) {
FileItem fItem = (FileItem) it.next();
if (fItem.isFormField()) {
// 普通文本框的值
System.out.println(fItem.getFieldName()+fItem.getString("UTF-8"));
} else { // 获取上传文件的值
String name = fItem.getName();
if(name != null && !("".equals(name))) {
name = name.substring(name.lastIndexOf(File.separator) + 1);
directory = new File("d://test");
directory.mkdirs();
String filePath = ("d://test")+ File.separator + name;
InputStream is = fItem.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
fos.write(buffer, 0, buffer.length);
}
fos.flush();
fos.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
out = response.getWriter();
out.print("{success:true, msg:'接收成功'}");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3、后台下载代码,SpringMVC
public List<String> UploadImage(HttpServletRequest request) {
List<String> list=new ArrayList<>();
String employee_no=request.getParameter("employee_no");
String tmppath=File.separator+"img"+File.separator +employee_no+File.separator;
String BasePath=request.getRealPath("/")+tmppath;
String BaseUrl=request.getLocalAddr()+":"+request.getLocalPort()+tmppath;
System.out.println(BaseUrl);
try {
File directory=new File(BasePath);
if(!directory.exists()){
directory.mkdirs();
}
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String name=file.getOriginalFilename();
System.out.println(file.getName()+name);
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
String ext=name.substring(name.lastIndexOf("."),name.length());
String filePath = BasePath+uuid+ext;
file.transferTo(new File(filePath));
list.add(BaseUrl+uuid+ext);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
HttpClient上传文件的更多相关文章
- [转]httpclient 上传文件、下载文件
用httpclient4.3 post方式推送文件到服务端 准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...
- Java使用HttpClient上传文件
Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...
- C#使用HttpClient上传文件并附带其他参数
HttpClient和MultipartFormDataContent(传送门)最低适用于.NET Framework 4.5版本 发送端代码 using (HttpClient client = n ...
- HttpClient 上传文件
/// <summary> /// 发送post请求 /// </summary> /// <param name="filePath">文件路 ...
- 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder
请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...
- HttpClient MultipartEntityBuilder 上传文件
文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...
- (十)HttpClient以multipart/form-data上传文件
原文链接:https://blog.csdn.net/wsdtq123/article/details/78888734 POST上传文件 最早的HTTP POST是不支持文件上传的,给编程开发带来很 ...
- https 协议下服务器根据网络地址下载上传文件问题
https 协议下服务器根据网络地址下载上传文件遇到(PKIX:unable to find valid certification path to requested target 的问题) 使用h ...
- HttpClient通过Post上传文件(转)
在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理. 但是项目中涉及到既要传递普通参数,也要传递多个文件 ...
随机推荐
- 使用mysqlbinlog恢复指定表
从整库备份的sql文件中导出某个表的sql语句时,vim查找到表的第一条INSERT语句后,按上下换行键计数INSERT语句的条数,然后按n yy复制,退出vim后,再新建一个文件,按p粘贴刚才的n条 ...
- Redis进阶实践之九 独立封装的RedisClient客户端工具类(转载9)
Redis进阶实践之九 独立封装的RedisClient客户端工具类 一.引言 今天开始有关Redis学习的第九篇文章了,以后肯定会大量系统使用Redis作为缓存介质,为了更好的更好的Redis,自己 ...
- ANg-线性回归算法
线性回归算法 linear regression 对于线性回归模型,我们期望对于样本数据集,通过假设函数,得出目标值 代价函数 m在这里指的是训练样本的数量 所以我们的目的就是得出代价函数(平方误差代 ...
- Structs复习 ActionMethod
action在执行的是时候 可以不执行excute方法 可以由自己制定 可以在action标签里指定 也可以在方法里动态指定 推荐使用后者 jar包 web.xml <?xml version ...
- JS----事件2
一 事件对象(event):与特定事件相关且包含有关该事件详细信息的对象 通过事件可以触发event对象的元素,鼠标的位置及状态,按下的键等等event对象只在事件发生的过程中才有效非IE浏览器里的e ...
- SQL Server - 使用 Merge 语句实现表数据之间的对比同步
表数据之间的同步有很多种实现方式,比如删除然后重新 INSERT,或者写一些其它的分支条件判断再加以 INSERT 或者 UPDATE 等.包括在 SSIS Package 中也可以通过 Lookup ...
- 使用Js控制ReactRouter路由
[使用Js控制ReactRouter路由] 首先引入PropTypes: const PropTypes = require('prop-types'); 然后定义context的router属性: ...
- javascript学习笔记(三):运算符、循环语句
javascript的运算符.条件语句.循环语句的使用方法大部分和c语言类似,但是值得注意的是,运算符中"=="和"==="的使用方法和c语言有区别:在java ...
- git桌面工具下载git源码
第一步,登陆githup,搜索自己需要查看的代码. 并复制clone url. 第二步,复制下载资源:选择菜单--FILE--CLONE
- Android学习路-UI控件