用edoc2实现上传和下载
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import java.io.*;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.*; @Component
public class FileUploadAndDownloadUtil {
private static Logger logger = LoggerFactory.getLogger(FileUploadAndDownloadUtil.class);
/**
* edoc2的url
*/
private static String baseUrl;
/**
* 集成登录密钥
*/
private static String integrationKey;
/**
* 登录用户名
*/
private static String loginName;
/**
* folderId 上传文件及下载文件关联的文件夹的id
*/
private static String folderId;
/*用户凭证*/
private static String token; /*登录*/
private static synchronized String CheckAndLogin() {
logger.info("CheckAndLogin......");
if (StringUtils.isEmpty(token))
return login();
boolean isEffective = checkToken();
if (isEffective)
return token;
else
return login();
} /*登录*/
private static String login() {
String regionUrl = baseUrl + "/api/services/org/UserLoginIntegrationByUserLoginName";
HttpClientRequest req = HttpClientRequest.newInstance();
JSONObject obj = new JSONObject();
obj.put("loginName", loginName);
obj.put("ipAddress", getLocalHost());
obj.put("integrationKey", integrationKey);
String result = req.postJson(regionUrl, obj.toJSONString());
logger.info("login:" + result);
JSONObject obj_result = JSON.parseObject(result);
token = obj_result.get("data").toString();
return token;
} /**
* 检查token是否有效
*
* @return boolean
*/
private static boolean checkToken() {
String url = baseUrl + "/api/services/Org/CheckUserTokenValidity?token=" + token;
HttpClientRequest req = HttpClientRequest.newInstance();
String result = req.get(url);
logger.info("checkToken:" + result);
JSONObject obj_result = JSON.parseObject(result);
boolean isContain = obj_result.containsKey("data");
if (!isContain)
return false;
return obj_result.getBoolean("data");
} /**
* 下载
*
* @param fileId 文件id
* @return 响应
* @throws IOException 异常
*/
public static HttpResponse download(String fileId) throws IOException, InterruptedException {
String token = CheckAndLogin(); String url = baseUrl + "/DownLoad/DownLoadCheck?token=" + token + "&fileIds=" + fileId;
HttpClientRequest req = HttpClientRequest.newInstance();
String result = req.get(url);
logger.info("downLoadCheck: {}", result); JSONObject obj_result = JSON.parseObject(result);
String blockurl;
/*除了0都是有问题*/
if (obj_result.getInteger("nResult") == 0) {
blockurl = baseUrl + "/downLoad/index?regionHash=" + obj_result.get("RegionHash") + "&async=false&token=" + token;
} else {
throw new DefException(obj_result.getString("msg"));
} // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Get请求
HttpGet httpGet = new HttpGet(blockurl); // 响应模型
// 由客户端执行(发送)Get请求
CloseableHttpResponse response1 = httpClient.execute(httpGet);
logger.info("downLoad: {}", blockurl);
return response1;
} /**
* 上传文件,这个和upload2是用的两种不同的方式来上传文件
*
* @param file 文件
* @return 返回上传的文件的相关的信息
* @throws IOException 异常
*/
public static String upload(MultipartFile file, String newfilenameString) throws IOException, InterruptedException {
String token = CheckAndLogin();
byte[] b = file.getBytes();
int filesize = b.length; String UploadId = UUID.randomUUID().toString();
JSONObject obj = new JSONObject();
obj.put("UploadId", UploadId);
/*15是个人文件夹的ParentId ,1044是crm文件管理*/
obj.put("ParentId", folderId);
obj.put("fileSize", filesize);
obj.put("name", newfilenameString);
obj.put("Token", token);
/*第一次请求*/
HttpClientRequest req = HttpClientRequest.newInstance();
String url = baseUrl + "/api/services/Transfer/StartUploadFile";
String json = req.postJson(url, obj.toString());
logger.info("StartUploadFile:" + json); JSONObject obj_result = JSON.parseObject(json);
String blockurl;
/*除了0都是有问题*/
if (obj_result.getInteger("Result") == 0) {
if (obj_result.getInteger("RegionId") == 1) {
blockurl = baseUrl + "/api/services/Transfer/UploadFileBlock";
} else {
blockurl = obj_result.getString("RegionUrl");
}
} else {
throw new DefException(obj_result.getString("Message"));
} int buffer = 819216;
int smallData = filesize % buffer;
int blockNum = filesize / buffer == 0 ? 1 : filesize / buffer;
try (InputStream bais = file.getInputStream()) {
for (int i = 0; i <= blockNum; i++) {
byte[] buffers = new byte[buffer]; //noinspection ResultOfMethodCallIgnored
bais.read(buffers);
String base64 = Base64.getEncoder().encodeToString(buffers);
JSONObject obj_block = new JSONObject();
obj_block.put("Token", token);
obj_block.put("dataSize", (i == blockNum ? smallData : buffer));
obj_block.put("FilePos", i * buffer);
obj_block.put("RegionHash", obj_result.getString("RegionHash"));
obj_block.put("BlockData", base64);
obj_block.put("uploadId", UploadId);
/*传输数据*/
String result_block = req.postJson(blockurl, obj_block.toJSONString());
logger.info("UploadFileBlock:" + result_block);
}
} catch (Exception e) {
throw new DefException("传输文件错误。");
}
String endurl = baseUrl + "/api/services/Transfer/EndUploadFile";
JSONObject obj_end = new JSONObject();
obj_end.put("Token", token);
obj_end.put("uploadId", UploadId);
obj_end.put("RegionHash", obj_result.getString("RegionHash"));
/*结束传输请求*/
String end_block = req.postJson(endurl, obj_end.toJSONString());
logger.info(end_block);
return obj_result.getString("FileId");
} /**
* 上传文件
*
* @param file 文件
* @param newfilenameString 新名字
* @return 返回上传的文件id
* @throws IOException 异常
*/
public static String upload2(MultipartFile file, String newfilenameString) throws IOException, InterruptedException {
String token = CheckAndLogin();
byte[] b = file.getBytes();
int filesize = b.length; String uploadId = UUID.randomUUID().toString();
String url = baseUrl + "/WebCore"; CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
HttpPost post = new HttpPost(url);
HttpEntity formEntity; List<NameValuePair> formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair("fileSize", "" + filesize));
formParams.add(new BasicNameValuePair("folderId", folderId));
formParams.add(new BasicNameValuePair("fileName", newfilenameString));
formParams.add(new BasicNameValuePair("module", "RegionDocOperationApi"));
formParams.add(new BasicNameValuePair("fun", "CheckAndCreateDocInfo"));
formParams.add(new BasicNameValuePair("type", file.getContentType()));
formParams.add(new BasicNameValuePair("size", "" + file.getSize()));
formParams.add(new BasicNameValuePair("attachType", "0"));
formParams.add(new BasicNameValuePair("fileModel", "UPLOAD"));
formParams.add(new BasicNameValuePair("token", token)); formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
post.setEntity(formEntity);
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
JSONObject str = JSON.parseObject(EntityUtils.toString(entity, "UTF-8")); logger.info(str.toJSONString());
if (str.getIntValue("result") != 0)
throw new DefException(str.getString("reason")); String blockurl = baseUrl + "/document/upload?token=" + token; /*注意:chunkSize不可以过大,否则会导致文件损坏*/
int chunkSize = 1024 * 1024 * 3;
int chunks = filesize / chunkSize == 0 ? 1 : filesize / chunkSize + 1;
int smallData = filesize % chunkSize;
try (InputStream ins = file.getInputStream()) {
for (int i = 0; i < chunks; i++) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("id", uploadId);
builder.addTextBody("name", newfilenameString);
builder.addTextBody("type", file.getContentType());
builder.addTextBody("lastModifiedDate", new Date().toString());
builder.addTextBody("size", "" + file.getSize());
builder.addTextBody("chunks", "" + chunks);
builder.addTextBody("chunk", "" + i);
builder.addTextBody("fileName", newfilenameString);
builder.addTextBody("blockSize", "" + (i + 1 == chunks ? smallData : chunkSize));
builder.addTextBody("chunkSize", "" + chunkSize);
builder.addTextBody("uploadId", uploadId);
builder.addTextBody("regionId", str.getJSONObject("data").getString("RegionId"));
builder.addTextBody("regionHash", str.getJSONObject("data").getString("RegionHash")); byte[] bytes = new byte[chunkSize];//每次读取文件的大小为5MB
//noinspection ResultOfMethodCallIgnored
ins.read(bytes); File tempfile = new File(String.valueOf(0));
FileOutputStream temfileStream = new FileOutputStream(tempfile);
temfileStream.write(bytes);
builder.addBinaryBody("file", tempfile);
// 把文件加到HTTP的post请求中
// builder.addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());
post.setURI(URI.create(blockurl));
HttpEntity multipart = builder.build();
post.setEntity(multipart);
temfileStream.close();
response = httpclient.execute(post);
HttpEntity responseEntity = response.getEntity();
String sResponse = EntityUtils.toString(responseEntity, "UTF-8");
logger.info(sResponse);
}
}
return str.getJSONObject("data").getString("FileId");
} /**
* @return 预览的url
*/
public static String getPreViewUrl() throws InterruptedException {
String token = FileUploadAndDownloadUtil.CheckAndLogin();
return baseUrl + "/jump.html?token=" + token + "&returnUrl=http://192.168.20.194/preview.html?fileid=1082";
} @Value("${EDOC2_BASE_URL}")
public void setBaseUrl(String baseUrl) {
FileUploadAndDownloadUtil.baseUrl = baseUrl;
} @Value("${INTEGRATIONKEY}")
public void setIntegrationKey(String integrationKey) {
FileUploadAndDownloadUtil.integrationKey = integrationKey;
} @Value("${EDOC2_LOGIN_NAME}")
public void setLoginName(String loginName) {
FileUploadAndDownloadUtil.loginName = loginName;
} @Value("${EDOC2_FOLDER_ID}")
public void setFolderId(String folderId) {
FileUploadAndDownloadUtil.folderId = folderId;
} /**
* 获取本地的ip
*
* @return ip
*/
private static String getLocalHost() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
throw new DefException("找不到HostAddress。");
}
}
}
用edoc2实现上传和下载的更多相关文章
- win7下利用ftp实现华为路由器的上传和下载
win7下利用ftp实现华为路由器的上传和下载 1. Win7下ftp的安装和配置 (1)开始->控制面板->程序->程序和功能->打开或关闭Windows功能 (2)在Wi ...
- Java实现FTP文件与文件夹的上传和下载
Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...
- java web学习总结(二十四) -------------------Servlet文件上传和下载的实现
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- Struts2入门(七)——Struts2的文件上传和下载
一.前言 在之前的随笔之中,我们已经了解Java通过上传组件来实现上传和下载,这次我们来了解Struts2的上传和下载. 注意:文件上传时,我们需要将表单提交方式设置为"POST" ...
- php实现文件上传与下载(上)
php实现文件的上传与下载是一个挺基本的功能,一般网站多多少少都会有这样的需求在内,当然不是说所有的文件都可以被上传,那这网络就太没有安全性可言了.因为接触php时间不长,今天写练练手,随笔也就是公开 ...
- SecureCRT上传和下载文件
SecureCRT上传和下载文件(下载默认目录) SecureCR 下的文件传输协议有ASCII .Xmodem .Ymodem .Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. ...
- SpringMVC文件上传和下载
上传与下载 1文件上传 1.1加入jar包 文件上传需要依赖的jar包 1.2配置部件解析器 解析二进制流数据. <?xml version="1.0" encoding=& ...
- 通读AFN②--AFN的上传和下载功能分析、SessionTask及相应的session代理方法的使用细节
这一部分主要研究AFN的上传和下载功能,中间涉及到各种NSURLSessionTask的一些创建的解析和HTTPSessionManager对RESTful风格的web应用的支持,同时会穿插一点NSU ...
- 每天一个linux命令(26):用SecureCRT来上传和下载
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem.文 ...
随机推荐
- @InitBinder的作用
由@InitBinder表示的方法,可以对WebDataBinder对象进行初始化.WebDataBinder是DataBinder的子类,用于完成由表单到JavaBean属性的绑定. @InitBi ...
- 高性能mysql 第11章 可扩展的mysql
可扩展性的定义:当增加资源以获得执行更多的工作系统能获得划算的同等提升. 向上扩展(垂直扩展):提升服务器的硬件性能. 向外扩展(水平扩展):一般都是复制,拆分,数据分片(sharding). 复制: ...
- MyEclipse使用教程:导航代码(一)
[MyEclipse CI 2019.4.0安装包下载] 无论是在文件之间导航还是在文件中导航,都可以使用大量导航工具来加快工作流程.目前这些导航工具可在MyEclipse,CodeMix中使用. 快 ...
- VCL界面控件DevExpress VCL Controls v19.1.3全新来袭
DevExpress VCL Controls是 Devexpress公司旗下最老牌的用户界面套包.所包含的控件有:数据录入,图表,数据分析,导航,布局,网格,日程管理,样式,打印和工作流等,让您快速 ...
- 多对多第三张表的创建方式 和 forms组件的使用
目录 一.多对多第三张表的创建 1. 全自动方式 (1)实现代码 (2)优点和不足 2. 纯手撸方式(了解) (1)实现代码 (2)优点和不足 3. 半自动方式(推荐使用) (1)实现代码 (2)优点 ...
- 服务器iis跟server-u 冲突
server-u 一定要配置域才可以监听21端口,不然一直ping 都是无效的.
- UVA 10900 So do you want to be a 2^n-aire?
#include<bits/stdc++.h> #include<stdio.h> #include<iostream> #include<cmath> ...
- R_Studio(教师经济信息)逻辑回归分析的方法和技巧
使用R语言对"教师经济信息"进行逻辑回归分析 (1)按3:1的比例采用简单随机抽样方法,创建训练集和测试集 (2)用训练集创建逻辑回归模型 (3)用测试集预测贷款结果,并用tabl ...
- JS框架_(Progress.js)圆形动画进度条
百度云盘 传送门 密码: 6mcf 圆形动画进度条效果: <!DOCTYPE html> <html lang="en"> <head> < ...
- Java并发编程的艺术笔记(九)——FutureTask详解
FutureTask是一种可以取消的异步的计算任务.它的计算是通过Callable实现的,多用于耗时的计算. 一.FutureTask的三种状态 二.get()和cancel()执行示意 三.使用 一 ...