Commit 84bdb0c6 by 宋祥

1.文件后台下载后推流到前端

parent de3c1c84
package com.baosight.hpjx.controller;
import com.baosight.hpjx.util.LogUtils;
import com.baosight.hpjx.util.MapUtils;
import com.baosight.hpjx.util.StringUtils;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.exception.PlatException;
import com.baosight.iplat4j.core.service.soa.XServiceManager;
import com.baosight.iplat4j.eu.dm.document.bos.s3.api.signed.SignedBosHelp;
import com.baosight.iplat4j.eu.dm.document.bos.s3.param.BosParamHelp;
import com.baosight.hpjx.util.FileUtils;
import com.google.common.base.Joiner;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
/**
* @author:songx
* @date:2024/3/14,14:26
*/
@Slf4j
@Controller
@CrossOrigin
@RequestMapping({"/file/download"})
public class FileDownloadController {
/**
* 更具docId下载文件
*
* @param docId
* @param request
* @param response
* @throws IOException
*/
@RequestMapping({"/{docId}"})
public void downloadUrl(@PathVariable String docId, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain; charset=UTF-8");
try {
EiInfo queryDocMapInfo = new EiInfo();
queryDocMapInfo.set("docId", docId);
queryDocMapInfo.set(EiConstant.serviceId, "S_EU_0102");
EiInfo returnInfo = XServiceManager.call(queryDocMapInfo);
Map docMap = returnInfo.getMap("docMap");
String s3UrlPrefix = MapUtils.getString(docMap, "url");
String fileName = MapUtils.getString(docMap, "resCname");
String returnUrlPrefix = BosParamHelp.disposeUrl(s3UrlPrefix);
Map<String, String[]> parameterMap = request.getParameterMap();
String returnUrl = this.getReturnUrlByParam(parameterMap, returnUrlPrefix);
if (StringUtils.isBlank(returnUrl)) {
String seconds = request.getHeader("seconds");
if (StringUtils.isBlank(seconds)) {
seconds = request.getParameter("seconds");
}
returnUrl = this.buildReturnUrl(seconds, fileName, returnUrlPrefix, s3UrlPrefix);
}
// 下载文件
if (StringUtils.isNotBlank(returnUrl)) {
FileUtils.downloadUrlFile(returnUrl, fileName, response);
} else {
throw new PlatException("文件地址异常");
}
} catch (Exception e) {
String msg = String.format("下载文件【%s】失败!原因:%s", docId, LogUtils.getMsg(e));
response.getWriter().write(msg);
}
}
private String getReturnUrlByParam(Map<String, String[]> parameterMap, String returnUrl)
throws UnsupportedEncodingException {
String returnUrl2 = "";
Map<String, String> paramMap = this.getParamMap(parameterMap);
paramMap.remove("code");
paramMap.remove("access_token");
paramMap.remove("seconds");
if (!paramMap.isEmpty() && paramMap.containsKey("X-Amz-Signature")) {
String queryString = this.buildQueryString(paramMap);
returnUrl2 = returnUrl + "?" + queryString;
}
return returnUrl2;
}
private String buildReturnUrl(String seconds, String fileName, String returnUrlPrefix, String s3UrlPrefix)
throws Exception {
URL s3Url = SignedBosHelp.getDownloadTempUrl(s3UrlPrefix, fileName, seconds);
String s3UrlParam = StringUtils.defaultIfEmpty(s3Url.getQuery(), "");
String returnUrl = returnUrlPrefix + "?" + s3UrlParam;
return com.baosight.iplat4j.eu.dm.util.FileUtils.returnDocUrlByEncodeFileName(returnUrl);
}
private Map<String, String> getParamMap(Map<String, String[]> parameterMap) {
Map paramMap = new HashMap();
Set<String> parameterSet = parameterMap.keySet();
Iterator parameterIterator = parameterSet.iterator();
while (parameterIterator.hasNext()) {
String next = (String) parameterIterator.next();
String[] valueArray = (String[]) parameterMap.get(next);
if (valueArray != null && valueArray.length != 0) {
String value = Joiner.on(",").join(valueArray);
paramMap.put(next, value);
}
}
return paramMap;
}
private String buildQueryString(Map<String, String> parameterMap) throws UnsupportedEncodingException {
StringBuilder strBuilder = new StringBuilder();
String rcd = MapUtils.getString(parameterMap, "response-content-disposition");
parameterMap.remove("response-content-disposition");
String next;
for (Iterator iterator = parameterMap.keySet().iterator(); iterator.hasNext();
strBuilder.append(next).append("=").append((String) parameterMap.get(next))) {
next = (String) iterator.next();
if (strBuilder.length() > 0) {
strBuilder.append("&");
}
}
if (StringUtils.isNotBlank(rcd)) {
strBuilder.append("&").append("response-content-disposition").append("=").append(
URLEncoder.encode(rcd, "UTF-8"));
}
return strBuilder.toString();
}
}
...@@ -28,7 +28,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -28,7 +28,7 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
@Component @Component
@Order(Ordered.HIGHEST_PRECEDENCE) @Order(Ordered.HIGHEST_PRECEDENCE)
public class MyGenericFilterFilter extends GenericFilterBean { public class MyGenericFilter extends GenericFilterBean {
@Override @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
......
package com.baosight.hpjx.core.oss;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.baosight.hpjx.util.StringUtils;
import com.baosight.iplat4j.core.ioc.spring.PlatApplicationContext;
import lombok.extern.slf4j.Slf4j;
/**
* OSS凭证
*
* @author:songx
* @date:2023/8/28,11:26
*/
@Slf4j
public class OssClientUtils {
private OssClientUtils() {
}
/**
* 初始化配置信息(纯粹就打印日志而已,因为会加载该类的全局变量)
*/
public static void init() {
AmazonS3 s3Client = Instance.s3Client;
log.info("初始化OSS客户端完成:isReady -> {}", s3Client != null);
}
/**
* 获取S3客户端
*
* @return
*/
public static AmazonS3 getS3Client() {
return Instance.s3Client;
}
/**
* 刷新客户端
*/
public static void refresh() {
Instance.refresh();
}
/**
* 初始化Instance
*
* @author:songx
* @date:2022/4/2,9:58
*/
private static class Instance {
/**
* 客户端实例
*/
private static AmazonS3 s3Client = buildAmazonS3();
/**
* 刷新S3客户端
*/
private static void refresh() {
s3Client = buildAmazonS3();
log.info("刷新OSS客户端完成:isReady->{}", s3Client != null);
}
/**
* 获取AmazonS3Client实例
*
* @return
*/
private static synchronized AmazonS3 buildAmazonS3() {
String accessKey = PlatApplicationContext.getProperty("iplat4j.admin.objectStorage.s3.accessKey");
String secretKey = PlatApplicationContext.getProperty("iplat4j.admin.objectStorage.s3.secretKey");
String endpoint = PlatApplicationContext.getProperty("iplat4j.admin.objectStorage.s3.endpoint");
if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey) || StringUtils.isBlank(endpoint)) {
return null;
}
AmazonS3ClientBuilder client = AmazonS3ClientBuilder.standard();
ClientConfiguration config = new ClientConfiguration();
config.setProtocol(com.amazonaws.Protocol.HTTPS);
config.setConnectionTimeout(10001);
config.setSignerOverride("S3SignerType");
client.setClientConfiguration(config);
client.setCredentials(new AWSStaticCredentialsProvider(
new BasicAWSCredentials(accessKey, secretKey)));
String url = endpoint + ":" + 80;
client.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, null));
return client.build();
}
}
}
package com.baosight.hpjx.core.oss;
import com.amazonaws.services.s3.AmazonS3;
import com.baosight.hpjx.util.AssertUtils;
import com.baosight.iplat4j.core.ioc.spring.PlatApplicationContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;
import java.io.File;
/**
* OSS工具类
*
* @author:songx
* @date:2023/8/28,11:25
*/
public class OssUtils {
// 桶名称
private static final String bucketName = PlatApplicationContext.getProperty(
"iplat4j.admin.objectStorage.s3.bucket");
/**
* 前端上传文件
*
* @param pageContext
* @return
* @throws Exception
*/
public static String uploadFile(PageContext pageContext) throws Exception {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
return null;
}
/**
* 上传文件
*
* @param key 默认不指定key的情况下,以文件内容的hash值作为文件名
* @param file
*/
public static void uploadFile(String key, File file) {
AmazonS3 client = OssClientUtils.getS3Client();
AssertUtils.isNull(client, "上传失败,OSS客户端未初始化,请检查");
client.putObject(bucketName, key, file);
}
}
...@@ -2,7 +2,9 @@ package com.baosight.hpjx.util; ...@@ -2,7 +2,9 @@ package com.baosight.hpjx.util;
import com.baosight.hpjx.core.constant.OSConstant; import com.baosight.hpjx.core.constant.OSConstant;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
...@@ -14,6 +16,9 @@ import java.io.FileWriter; ...@@ -14,6 +16,9 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.text.DecimalFormat; import java.text.DecimalFormat;
...@@ -25,12 +30,15 @@ import java.util.Objects; ...@@ -25,12 +30,15 @@ import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
/** /**
* 文件工具类 * 文件工具类
* *
* @author:songx * @author:songx
* @date:2016/3/26,11:54 * @date:2016/3/26,11:54
*/ */
@Slf4j
public class FileUtils extends org.apache.commons.io.FileUtils { public class FileUtils extends org.apache.commons.io.FileUtils {
/** /**
...@@ -454,4 +462,48 @@ public class FileUtils extends org.apache.commons.io.FileUtils { ...@@ -454,4 +462,48 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
} }
/**
* InputStream
*
* @param url
*/
public static InputStream downloadStreamFromUrl(String url) throws IOException {
URL httpUrl = new URL(url);
return httpUrl.openStream();
}
/**
* 下载文件到前端
*
* @param url
* @param fileName
* @param response
*/
public static void downloadUrlFile(String url, String fileName, HttpServletResponse response) throws IOException {
// 设置响应类型,图片直接预览
if ("jpg/jpeg/png/bmp/gif/tif/icon/ico".contains(
fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase())) {
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
} else {
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
}
try (InputStream is = downloadStreamFromUrl(url);
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
byte[] buffer = new byte[1024];
while (true) {
int len = is.read(buffer);
if (len == -1) {
break;
}
outputStream.write(buffer, 0, len);
}
outputStream.flush();
} catch (IOException e) {
throw e;
}
}
} }
...@@ -72,7 +72,21 @@ public class LogUtils { ...@@ -72,7 +72,21 @@ public class LogUtils {
} }
inInfo.setMsg(msg.concat(e.getMessage())); inInfo.setMsg(msg.concat(e.getMessage()));
} }
/**
* 转换系统异常,业务异常
*
* @param e
* @return
*/
public static String getMsg(Throwable e) {
if (e instanceof PlatException) {
return e.getMessage();
} else {
return "服务异常,请稍后重试!";
}
}
/** /**
* 打印日志 * 打印日志
* *
......
...@@ -73,7 +73,11 @@ function message(msg) { ...@@ -73,7 +73,11 @@ function message(msg) {
* @returns {string} * @returns {string}
*/ */
function downloadHref(docId) { function downloadHref(docId) {
return IPLATUI.CONTEXT_PATH + ("run" == projectEnv ? ('/docFileDownload/' + docId) // S3地址有外网
// return IPLATUI.CONTEXT_PATH + ("run" == projectEnv ? ('/docFileDownload/' + docId)
// : ('/EU/DM/EUDM06.jsp?docId=' + docId));
// S3地址无外网
return IPLATUI.CONTEXT_PATH + ("run" == projectEnv ? ('/file/download/' + docId)
: ('/EU/DM/EUDM06.jsp?docId=' + docId)); : ('/EU/DM/EUDM06.jsp?docId=' + docId));
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment