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 ...
随机推荐
- LinkedHashSet
特点: 有序 , 唯一 底层的数据结构为: 链表和哈希表 , 链表保证有序 , 哈希表保证唯一 import java.util.LinkedHashSet; public class Demo2_L ...
- Windows10下Anaconda虚拟环境下安装pycocotools
0 - 步骤 安装visualcppbuildtools_full.exe(链接:https://blog.csdn.net/u012247418/article/details/82314129) ...
- Redis Sentinel 高可用服务架构搭建
https://www.cnblogs.com/xishuai/p/redis-sentinel.html
- Unicode浅析——调用科大讯飞语音合成接口(日语)所遇到的天坑
如题,最近做的项目需要调用科大讯飞的语音合成接口,将日文合成日语.然后坑爹的是跟我对接的那一方直接扔过来一份接口文档,里面并未提及日语合成所需要的参数.中文.英文合成倒是没问题,就这个日语合成的音频始 ...
- Dubbo -- 关于 api接口调用不使用强依赖
首先,我们都知道 Dubbo 调用api 需要提供暴露 接口, 消费端才通过 ZK 可以调用 通常我们都会使用 提供 api jar包 的方式 使用 这样既方便又快捷 简单 只需要在spr ...
- Day9作业:socket之FTP工具
代码传的太累,直接发个github的链接吧! https://github.com/ccorzorz/Socketserver_FTP 上两张图给抛砖引玉下吧: 后台管理: FTP程序,包括客户端和s ...
- Django文档
https://docs.djangoproject.com/zh-hans/2.1/
- AFNetWorking实现参数以body传输请求数据
/** * 异步POST请求:以body方式,支持数组 * * @param url 请求的url * @param body body数据 * @param success 成功回调 * @para ...
- PostgreSQL创建database默认编码为UTF-8
在psql中执行如下代码: create database logdb encoding='UTF8';
- jquery取选中的checkbox的值
一. 在html的checkbox里,选中的话会有属性checked="checked". 如果用一个checkbox被选中,alert这个checkbox的属性"c ...