文件下载
@GetMapping(value = "/v1/files/**/{file_name:.+}")
public void downFile(@PathVariable("file_name") String fileName, HttpServletResponse response, HttpServletRequest request) {
// String uploadPath = IFlieServiceRpc.findByStrategyKey(uploadDir);
String url = request.getServletPath();//获取url
url = url.substring(url.lastIndexOf("files")).replace("files/", "");
String uploadPath = null;
String os = OSNameUtil.getOSname();
if ("Windows".equals(os)) {
uploadPath = winuploadDir;
} else if ("Linux".equals(os)) {
uploadPath = linuxuploadDir;
}
//截取时间戳
String filename = "";//不带时间戳的文件名
String ownFilePathString = "";//自定义文件路径
if (url.lastIndexOf("/") > 0) {
filename = url.substring(url.lastIndexOf("/") + 1);
ownFilePathString = url.substring(0, url.lastIndexOf("/") + 1);
} else {
filename = url;
}
if (filename.indexOf("_") > 0) {
filename = filename.substring(filename.indexOf("_") + 1);
}
String path = uploadPath + File.separator + url;
String path1 = uploadPath + File.separator + ownFilePathString + filename;
//判断文件是否存在
File file2 = new File(path);
if (!file2.exists()) {
LOGGER.equals("文件不存在");
throw new SBRException("文件不存在");
}
String getSm4Key = null;
try {
getSm4Key = PropertyUtil.getProperty("sm4");
if (getSm4Key != null && !"".equals(getSm4Key)) {
SM4Utils.decryptFile(path, path1, getSm4Key);
} else {
renameFile(path, path1);
//path1=path;
}
} catch (IOException e1) {
if (getSm4Key != null && !"".equals(getSm4Key)) {//解析后的文件需要删除
File file = new File(path1);
file.delete();
}
LOGGER.error("获取sm4报错,错误原因:" + e1);
throw new SBRException("获取sm4报错,错误原因:" + e1);
}
File file = new File(path1);
FileInputStream fis =null;
try {
if (file.exists()) {
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((file.getName()).getBytes("GB2312"), "ISO8859-1"));
response.setContentLength((int) file.length());
response.setContentType("application/octet-stream");// 定义输出类型
fis = new FileInputStream(file);
BufferedInputStream buff = new BufferedInputStream(fis);
byte[] b = new byte[1024];// 相当于我们的缓存
long k = 0;// 该值用于计算当前实际下载了多少字节
OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
// 开始循环下载
while (k < file.length()) {
int j = buff.read(b, 0, 1024);
k += j;
myout.write(b, 0, j);
}
myout.flush();
myout.close();
buff.close();
if (getSm4Key != null && !"".equals(getSm4Key)) {
file.delete();
}
}
} catch (Exception e) {
if (getSm4Key != null && !"".equals(getSm4Key)) {//解析后的文件需要删除
file.delete();
}
LOGGER.error("文件下载流错误,错误原因:" + e);
throw new SBRException("文件下载流错误,错误原因:" + e);
} finally {
if(fis!=null){
try {
fis.close();
fis=null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
if (getSm4Key == null && "".equals(getSm4Key)) {//没加密的文件需要处理
renameFile(path1, path);
}
} catch (IOException e) {
LOGGER.error("重命名失败,失败原因:" + e);
throw new SBRException("重命名失败,失败原因:" + e);
}
}
}
Feign接口调用
@FeignClient("prometheus-file")
public interface FileFeignClient {
@GetMapping(value = "/file/api//v1/files/{file_name}",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
Response downFile(@PathVariable("file_name") String fileName);
}
/**
* 将文件写入随机文件,并返回路径
* @param fileName 文件名称
* @return
*/
public String getFilePath(String fileName){
InputStream inputStream = null;
//获得文件流
Response response =fileFeignClient.downFile(fileName);
Response.Body body = response.body();
String filePath ="";
FileOutputStream fos = null;
try {
//获取response中的文件流
inputStream = body.asInputStream();
// byte[] b = new byte[inputStream.available()];
// inputStream.read(b);
//临时目录
String folder=System.getProperty("java.io.tmpdir");
int random = (int)(1+Math.random()*(10-1+1));
String sj = String.valueOf(DateUtil.getCurrentDate().getTime());
//临时路径+文件名称
filePath = folder + sj+random+fileName.substring(fileName.lastIndexOf("."));
//写入文件
fos= new FileOutputStream(filePath);
byte[] c = new byte[1024];
int length;
while((length= inputStream.read(c))>0){
fos.write(c,0,length);
}
} catch (IOException e1) {
e1.printStackTrace();
}finally{
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
@GetMapping(value = "/v1/notified_tasks/html")
public Map getHtmlBody(String notifiedTypeId){
NotifiedType notifiedType = notifiedTypeService.findById(notifiedTypeId);//查找对应类型
if(StringUtils.isEmpty(notifiedType.getNotifiedAttr())){
Map map = new HashMap();
map.put("htmlStr", "");
map.put("fileName", notifiedType.getNotifiedAttr());
return map;
}
//获取临时文件路径
String filePath = getFilePath(notifiedType.getNotifiedAttr());
String str = "";
File file = new File(filePath);
try {
str = PoiUtils.officeToHtml(getUploadPath(), filePath);//获取html字符串
file.delete();//删除临时文件
} catch (Exception e) {
file.delete();//删除临时文件
e.printStackTrace();
}
if(str.equals("false")){
str="";
}
Map map = new HashMap();
map.put("htmlStr", str);
map.put("fileName", notifiedType.getNotifiedAttr());
return map;
}