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. sql 替换字段中的部分字符,替换指定字符

    把列中凡是有2011的全部修改成2014,如 lieming 里的201101131431改成201401131431,写法:   update tab set lieming = replace(l ...

  2. GPS坐标转换 百度地图API调用

    1 如果GPS输出的值是DD.DDDDDDDD格式的,直接调用地图API的转换函数处理,就可以正常显示2 如果GPS输出的值是DD.MMMMMMMM格式的,就需要先进行分转度处理,然后再调API,就可 ...

  3. swift视图的添加及层次变动和基本动画

    // 一般的我们添加一个视图到父视图都是通过 /* let v1 = UIView(frame:CGRectMake(100,200,30,50)) self.view.addSubview(v1) ...

  4. waffit防火墙检测

    Waffit是一款Web应用防火墙检测工具,检测防火墙保护的站点是在渗透测试中非常重要的一步.如果没有对WAF进行配置,有时候可能存在漏洞.在渗透测试和风险评估中分析WAF也是非常重要的.通过编码攻击 ...

  5. 05_ssm基础(三)之Spring基础

    11.spring入门引导 12.spring_HelloWord程序 实现步骤: 0.找到spring压缩包,并解压 1.拷贝jar包 2.添加主配置文件(官方文档约28页) 3.在测试中使用 13 ...

  6. 03_java基础(六)之CRUD实现

    1.简单实现 package com.day01.station.dao; /** * Created by Administrator on 2018/2/1. */ import java.sql ...

  7. CentOS7 安装 GitLab

    虽然GitHub已经很好了,但是我们必须联上公网才可以使用并且如果不付费的话,你的代码在网上就是公开的!但是在企业环境中,我们公司的代码不希望被公开并且也不想付费给GitHub,这时怎么办呢?我们可以 ...

  8. 1.5.6、CDH 搭建Hadoop在安装之前(定制安装解决方案---使用Cloudera Manager模板创建CDH群集)

    使用Cloudera Manager模板创建CDH群集 您可以通过从Cloudera Manager管理的现有CDH群集导出群集模板来创建新的CDH群集.然后,您可以修改模板并使用它在新的主机集上创建 ...

  9. centos7防火墙以设置以及关闭selinux

    一.CentOS 7.X 关闭SELinux 1.查看 getenforce permissive 或者 enforcing模式 2.临时设置 setenforce 1 成为permissive模式 ...

  10. Gamma Correction

    [Gamma Correction] 磁盘上存储的纹理可分为Linear Texture.Gamma Texture. sRGB sampling allows the Unity Editor to ...