客户端将文件转换为流发送:

依赖的包:

<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提交文件流 及服务端接收文件流的更多相关文章

  1. java在线聊天项目0.4版本 制作服务端接收连接,客户端连接功能 新增客户端窗口打开时光标指向下边文本域功能,使用WindowListener监听WindowAdapter

    建一个服务端类ChatServer,用于设置端口接收连接 package com.swift; import java.io.IOException; import java.net.ServerSo ...

  2. Java 后端开发常用的 10 种第三方服务

    请肆无忌惮地点赞吧,微信搜索[沉默王二]关注这个在九朝古都洛阳苟且偷生的程序员.本文 GitHub github.com/itwanger 已收录,里面还有我精心为你准备的一线大厂面试题. 严格意义上 ...

  3. axis2框架用wsdl文件生成的服务端MessageReceiveInOut文件注意事项

    在用axis2生成服务端文件和客户端文件,当客户端文件调用服务端文件时,都是通过wsdl文件生成的 配置文件进行相互的调用. 在一开始做开发测试的时候,通过soapUI进行调用接口的时候,可以调用成功 ...

  4. httpurlConnection客户端发送文件与服务端接受文件

    import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; ...

  5. zabbix服务端接收的数据类型,便于编写脚本向服务端提交数据

    1.数据类型1:zabbix_agent执行脚本提交字典 UserParameter=tcp_port_listen,/usr/local/zabbix/share/script/get_game_p ...

  6. C# 客服端上传文件与服务器器端接收 (简单代码)

    简单代码: /*服务器端接收写入 可以实现断点续传*/ public string ConnectUpload(string newfilename,string filepath,byte[] fi ...

  7. 从app上传图片到php,再上传到java后端服务器的方法一览

    在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的.也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依 ...

  8. 从app上传图片到php,再上传到java后端服务器的方法一条龙服务

    在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的.也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依 ...

  9. java io流(字节流)复制文件

    java io流(字节流) 复制文件 //复制文件 //使用字节流 //复制文本文件用字符流,复制其它格式文件用字节流 import java.io.*; public class Index{ pu ...

随机推荐

  1. ctl +→ = MAC 触控板三指手势

    我只想发一个这个:一直用外接显示器,但是不舍得抛弃全屏程序的切换,即:触控板三指手势. 期间各种百度无果,最多找到出最多的是触发角: 今天终于发现了:ctl +→  =  MAC 触控板三指手势 (外 ...

  2. ARM 之一 ELF文件、镜像(Image)文件、可执行文件、对象文件 详解

    [转]https://blog.csdn.net/ZCShouCSDN/article/details/100048461 ELF 文件规范   ELF(Executable and Linking ...

  3. osgGA::KeySwitchMatrixManipulator 跟随

    #ifdef _WIN32 #include <Windows.h> #endif // _WIN32 #include <osg/Group> #include <os ...

  4. Javescript——数据类型

    原文链接:Understanding Data Types in JavaScript Data types are used to classify one particular type of d ...

  5. 【用户体验】Google关闭标签的体验

    https://www.uisdc.com/hunter/0221334485.html 在优设-细节猎人里有不少好案例.

  6. MySQL必知必会:组合查询(Union)

        MySQL必知必会:组合查询(Union) php mysqlsql  阅读约 8 分钟 本篇文章主要介绍使用Union操作符将多个SELECT查询组合成一个结果集.本文参考<Mysql ...

  7. django model的update时auto_now不被更新的原因

    gmt_create自动添加auto_now_add:gmt_modify自动更新auto_now class CommonInfo(models.Model): """ ...

  8. go基础系列 第一章 go基础语法

    0.前言 1. go定义变量的几种方式 2. go内建变量类型 3. 常量的定义 4. go枚举 5. go的if语句 零. go语言的换行 go语言对换行很有讲究, 如果想换行,必须有一个逗号, 否 ...

  9. css实现可伸缩的搜索框

    效果图: 代码: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" ...

  10. Java 七牛云存储与下载

    七牛云的文件上传和下载(私有空间) 1.本篇博客参考网址 https://blog.csdn.net/peaceful000/article/details/53171578 https://blog ...