Java后端HttpClient Post提交文件流 及服务端接收文件流
客户端将文件转换为流发送:
依赖的包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public static void main(String[] args) throws IOException {
DataInputStream in = null;
OutputStream out = null;
HttpURLConnection conn = null;
JSONObject resposeTxt = null;
InputStream ins = null;
ByteArrayOutputStream outStream = null;
try {
// URL url = new URL("http://192.168.3.11:8081/mes-boot-doc/test/fileupload?fileName=shafei.xls");
URL url = new URL("http://localhost:8081/mes-boot-doc/test/fileupload?fileName=shafei.xls"); conn = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/html");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Charsert", "UTF-8");
conn.connect();
conn.setConnectTimeout(10000);
out = conn.getOutputStream(); File file = new File("C:/Users/Dell/Desktop/print/shafei.xls");
in = new DataInputStream(new FileInputStream(file)); int bytes = 0;
byte[] buffer = new byte[1024];
while ((bytes = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
out.flush(); // 返回流
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
ins = conn.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
while ((count = ins.read(data, 0, 1024)) != -1) {
outStream.write(data, 0, count);
}
data = null;
resposeTxt = JSONObject.parseObject(new String(outStream
.toByteArray(), "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (ins != null) {
ins.close();
}
if (outStream != null) {
outStream.close();
}
if (conn != null) {
conn.disconnect();
}
}
}
服务端接收文件流生成文件:
@PostMapping("/fileupload")
public String uploadFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
String fileName = request.getParameter("fileName");
log.info("filename:"+fileName);
// String fileName ="shafei.xls";
// String fileFullPath = "C:/Users/Dell/Desktop/print/test/" + fileName;
String fileFullPath = "/root/uploadfile/apache-tomcat-8.5.42/" + fileName; InputStream input = null;
FileOutputStream fos = null;
try {
input = request.getInputStream();
File file = new File("/root/uploadfile/apache-tomcat-8.5.42/");
if(!file.exists()){
file.mkdirs();
}
fos = new FileOutputStream(fileFullPath);
int size = 0;
byte[] buffer = new byte[1024];
while ((size = input.read(buffer,0,1024)) != -1) {
fos.write(buffer, 0, size);
} //响应信息 json字符串格式
Map<String,Object> responseMap = new HashMap<String,Object>();
responseMap.put("flag", true); //生成响应的json字符串
String jsonResponse = JSONObject.toJSONString(responseMap);
sendResponse(jsonResponse,response);
} catch (IOException e) {
//响应信息 json字符串格式
Map<String,Object> responseMap = new HashMap<String,Object>();
responseMap.put("flag", false);
responseMap.put("errorMsg", e.getMessage());
String jsonResponse = JSONObject.toJSONString(responseMap);
sendResponse(jsonResponse,response);
} finally{
if(input != null){
input.close();
}
if(fos != null){
fos.close();
}
} return null;
} /**
* 返回响应
*
* @throws Exception
*/
private void sendResponse(String responseString,HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=UTF-8");
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(responseString);
pw.flush();
} finally {
IOUtils.closeQuietly(pw);
}
}
Java后端HttpClient Post提交文件流 及服务端接收文件流的更多相关文章
- java在线聊天项目0.4版本 制作服务端接收连接,客户端连接功能 新增客户端窗口打开时光标指向下边文本域功能,使用WindowListener监听WindowAdapter
建一个服务端类ChatServer,用于设置端口接收连接 package com.swift; import java.io.IOException; import java.net.ServerSo ...
- Java 后端开发常用的 10 种第三方服务
请肆无忌惮地点赞吧,微信搜索[沉默王二]关注这个在九朝古都洛阳苟且偷生的程序员.本文 GitHub github.com/itwanger 已收录,里面还有我精心为你准备的一线大厂面试题. 严格意义上 ...
- axis2框架用wsdl文件生成的服务端MessageReceiveInOut文件注意事项
在用axis2生成服务端文件和客户端文件,当客户端文件调用服务端文件时,都是通过wsdl文件生成的 配置文件进行相互的调用. 在一开始做开发测试的时候,通过soapUI进行调用接口的时候,可以调用成功 ...
- httpurlConnection客户端发送文件与服务端接受文件
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; ...
- zabbix服务端接收的数据类型,便于编写脚本向服务端提交数据
1.数据类型1:zabbix_agent执行脚本提交字典 UserParameter=tcp_port_listen,/usr/local/zabbix/share/script/get_game_p ...
- C# 客服端上传文件与服务器器端接收 (简单代码)
简单代码: /*服务器端接收写入 可以实现断点续传*/ public string ConnectUpload(string newfilename,string filepath,byte[] fi ...
- 从app上传图片到php,再上传到java后端服务器的方法一览
在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的.也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依 ...
- 从app上传图片到php,再上传到java后端服务器的方法一条龙服务
在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的.也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依 ...
- java io流(字节流)复制文件
java io流(字节流) 复制文件 //复制文件 //使用字节流 //复制文本文件用字符流,复制其它格式文件用字节流 import java.io.*; public class Index{ pu ...
随机推荐
- Android:系统自定义鼠标样式切换
一.APP通过View修改鼠标样式 app view上修改鼠标样式比较简单,通过 hover event 获取鼠标坐标并使用如下方法修改为自定义图片: getWindow().getDecorView ...
- JAVA书写格式规范
1,大括号要对齐,并且成对写 2,左大括号前面有空格 3,遇到左大括号要缩进,Tab 4,方法和程序块之间加空行让程序看起来清晰 5,并排语句之间加空格,例如for语句 6,运算符两侧加空格
- ifc tree
ViewerWidget* viewerWidget = new ViewerWidget(ifcModel); viewerWidget ->setRootNode(ifcModel-> ...
- plupload上传大文件
大容量文件上传早已不是什么新鲜问题,在.net 2.0时代,HTML5也还没有问世,要实现这样的功能,要么是改web.config,要么是用flash,要么是用一些第三方控件,然而这些解决问题的方法要 ...
- JS时间转换,url编码,jquery返回类型等问题
1.当时间被转换为json格式后会被转换成 /Date(...)/ 这种格式,其中...为时间转换成妙后的一串整数 function changeDateFormat(cellval) { )); v ...
- js实现div吸顶效果
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script> < ...
- C语言 班级档案管理系统实现
代码地址:github地址 班级档案管理系统 原题目要求是对一个有N个学生的班级,通过该系统实现对该班级学生的基本信息进行录入. 显示.修改.删除.保存等操作的管理. 由于个人需要,我单独将项目改造为 ...
- poj1584(判断凸包+求点到线段的距离)
题目链接:https://vjudge.net/problem/POJ-1584 题意:首先要判断凸包,然后判断圆是否在多边形中. 思路: 判断凸包利用叉积,判断圆在多边形首先要判断圆心是否在多边形中 ...
- 【最后一战】NOI2019游记
NOI2019 游记 报到日 -1 打了一场LOJ发现rk5,听完cy讲T1后感觉自己非常智障--AK的那位老哥好强啊qwq 窝在宾馆里打打游戏敲敲板子 饥荒真好玩 等着明天去报道 要退役了反而心情平 ...
- Feign【开启GIZP压缩】
SpringCloudFeign支持对请求和响应进行gzip压缩,以此来提高通信效率. 1.搭建gzip-demo工程 1.1.工程依赖: <parent> <groupId> ...