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上传文件的更多相关文章

  1. [转]httpclient 上传文件、下载文件

    用httpclient4.3 post方式推送文件到服务端  准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...

  2. Java使用HttpClient上传文件

    Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...

  3. C#使用HttpClient上传文件并附带其他参数

    HttpClient和MultipartFormDataContent(传送门)最低适用于.NET Framework 4.5版本 发送端代码 using (HttpClient client = n ...

  4. HttpClient 上传文件

    /// <summary> /// 发送post请求 /// </summary> /// <param name="filePath">文件路 ...

  5. 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder

    请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...

  6. HttpClient MultipartEntityBuilder 上传文件

    文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...

  7. (十)HttpClient以multipart/form-data上传文件

    原文链接:https://blog.csdn.net/wsdtq123/article/details/78888734 POST上传文件 最早的HTTP POST是不支持文件上传的,给编程开发带来很 ...

  8. https 协议下服务器根据网络地址下载上传文件问题

    https 协议下服务器根据网络地址下载上传文件遇到(PKIX:unable to find valid certification path to requested target 的问题) 使用h ...

  9. HttpClient通过Post上传文件(转)

    在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理. 但是项目中涉及到既要传递普通参数,也要传递多个文件 ...

随机推荐

  1. Service的启动,绑定,绑定后通信,跨应用绑定,跨应用绑定后通信

    Service介绍: 与Acitivity平级的Android四大组件之一,对比Activity而言,就是没有交互界面,且可以一直在后台执行,只用于处理下载,I/O等长时间信息交流的任务. Servi ...

  2. C++复习:纯虚函数和抽象类

    纯虚函数和抽象类 1基本概念 2抽象类案例   3抽象类在多继承中的应用 C++中没有Java中的接口概念,抽象类可以模拟Java中的接口类.(接口和协议) 3.1有关多继承的说明 工程上的多继承 被 ...

  3. VC中BSTR、Char和CString类型的转换

    1.char*转换成CString 若将char*转换成CString,除了直接赋值外,还可使用CString::format进行.例如: char chArray[] = "This is ...

  4. Think you can pronounce these 10 words correctly? You might be

    Think you can pronounce these 10 words correctly?  You might be surprised! Share Tweet Share Tagged ...

  5. LeetCode OJ 80. Remove Duplicates from Sorted Array II

    题目 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  6. VBS处理AD帐号密码到期提醒的脚本[zt]

    原文:https://gallery.technet.microsoft.com/scriptcenter/f7f5f7ed-14ee-4d0e-81c2-7d95ce7e08f5 '======== ...

  7. JAVAWEB 一一 框架整合(SSH,Spring+Struts2+Hibernate IOC/DI AOP声明式事务处理 定时任务)

    package org.springframework.orm.hibernate3; import java.io.Serializable; import java.util.List; impo ...

  8. py3 读入和写入csv,txt文件

    import numpy as npimport pandas as pdimport time import datetimeimport csv http://pandas.pydata.org/ ...

  9. CSS 颜色术语

    术语和概念在理科学习非常重要.CSS中有些关键的术语的. 对比度 对比度是指前景色和背景色之间的差距.当前景颜色和背景色之间的对比度较低时,文本就难以阅读.这对视觉障碍或色盲来说更严重. 透明度 透明 ...

  10. Oracle登录后提示ORA-12154:TNS:无法解析指定的连接标识符

    下午重装系统,安装Oracle,设置了首选项的Oracle主目录名和OCI库,但还是提示ORA-12154:TNS:无法解析指定的连接标识符 纠结了好久,发现刚装系统没设置Oacle数据库的系统环境变 ...