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进行相应的处理. 但是项目中涉及到既要传递普通参数,也要传递多个文件 ...
随机推荐
- docker之container
转自:https://www.cnblogs.com/jsonhc/p/7760144.html 运行一个container的本身就是开启一个具有独立namespace的进程 进程有自己的网络,文件系 ...
- 尚硅谷springboot学习2-微服务
2014年,martin flowler发表关于微服务的博客 微服务是一种架构风格:一个应用应该是一组小型服务:可以通过HTTP的方式进行互通: 单体应用:ALL IN ONE 微服务:每一个功能元素 ...
- java后端实习生面试题目
1.编程题:java从10000到99999找到AABB类型 public class Test1 { public static void main(String[] args) { String ...
- upupw
https://sourceforge.net/projects/upupw/files/ANK/
- How to Pronounce the Numbers 1 – 10
How to Pronounce the Numbers 1 – 10 Share Tweet Share Tagged With: Numbers Numbers are something you ...
- 点击li往数组添加对应li的id再点击移除,根据是否有class判断
if($(this).hasClass('click')){ $(this).removeClass('click'); var idAPP = $(this).attr('id'), index = ...
- SQL Server 用角色(Role)管理数据库权限
当数据库越来越多,连接到数据库的应用程序,服务器,账号越来越多的时候,为了既能达到满足账号操作数据权限需求,又不扩大其操作权限,保证数据库的安全性,有时候需要用角色来参与到权限管理中,通过角色做一个权 ...
- wParam与lParam的区别
wParam与lParam的区别 lParam 和 wParam 是宏定义,一般在消息函数中带这两个类型的参数,通常用来存储窗口消息的参数. LRESULT CALLBACK WindowProc(H ...
- Oracle 查询表的字段注释
SELECT TABLE_NAME, COLUMN_NAME, COMMENTSFROM USER_COL_COMMENTSWHERE TABLE_NAME = 'TB_MENU';
- 苹果笔记本 如何配置成php开发系统
方法一 启动内置的apace 打开终端输入命令 停止服务:sudo /usr/sbin/apachectl stop 开启服务:sudo /usr/sbin/apachectl start 重启服务: ...