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进行相应的处理. 但是项目中涉及到既要传递普通参数,也要传递多个文件 ...
随机推荐
- vue:绑定数据的vue页面加载会闪烁问题
1:在挂在数据的容器加上属性 v-cloak 2:在css中添加如下代码 但有时候还是会不起作用,可能原因有两个 2.1:display属性被更高权限的display属性覆盖了,我们增加权限就好了 2 ...
- vue:再vue-cli项目中使用window以及调用window上的方法
一: 1:在main.js中 Vue.prototype.myfunction = function() {/*你的自定义Vue方法*/} 2:在mounted(或其他生命周期中) 或者 method ...
- JAVA_Package
Javaの名前空間の仕組みの1つにパッケージがあります.大規模開発では必須の概念です.また.他人の作ったコードの再利用という観点でも.パッケージを正しく活用する必要があります. ・完全修飾名:パッケー ...
- Java中Asm包有什么用?
ASM能做什么 我们都知道,一般情况下,Class文件是通过javac编译器产生的,然后通过类加载器加载到虚拟机内,再通过执行引擎去执行. 现在我们可以通过ASM的API直接生成符合Java虚拟机规范 ...
- U3D MemoryProfiler
MemoryProfiler Unity 5.3a4 has a new very lowlevel memory profiler API. It can tell you which object ...
- Docker容器硬盘动态扩容
扩容容器 docker容器默认的空间是10G,如果想指定默认容器的大小(在启动容器的时候指定),可以在docker配置文件里通过dm.basesize参数指定,比如 1 docker -d --sto ...
- linux 3.10 tcp的accept测试
net.ipv4.tcp_abort_on_overflow 为 0 有个兄弟跟我说accept的时候,如果故意不去accept,那么客户端connect的时候,一开始很快,后来就很慢: connec ...
- 拓展jquery js动态添加html代码 初始化数据
1 /** * 新增数据筛选 */ (function () { $.filterEvent = function(options){ var _this = this; var defaults = ...
- Spring格式化注解
Spring Framework 3.0发布了.这里我们介绍其中的一个:用于格式化的注解.简介 Spring 3 提供了两个可以用于格式化数字.日期和时间的注解@NumberFormat和@DateT ...
- servlet(2)response常用方法
详细的response 学习笔记是: 输出到前台的的方法 1:使用OutputStream流向客户端浏览器输出中文数据 2:使用PrintWriter流向客户端浏览器输出中文数据 3:使用Output ...