前景:
最近开发中有这样一个场景
服务器A中放了一个接口项目,用于获取本服务的文件。
服务器B中放了一个接口项目,用于获取本服务的文件。
服务器C中放了一个前端项目,用于获取服务器B或者服务器C的文件.
但是服务器C只能访问到服务器B,服务器B能访问到服务器A。
服务器C向服务器B传参发起请求,服务器B获取到参数后判断服务器C需要的文件是否存在本服务器中,不存在则向服务器A发起请求并携带参数。
服务器A找到文件后,将文件转成Base64编码响应给服务器B,服务器B接受到服务器A的相应后继续相应给服务器C。
此时服务器C的前端接收到返回的Base64编码字符串,将字符串转换成文件在浏览器中下载。
StringUtil.class工具类在其他文章中有源码。
服务器A
/**
* 获取文件
*/
@RequestMapping(value="/getfileByName")
public String getfileByName(@RequestParam(value = "filePath") String filePath)
{
String resStr = ""
if(StringUtil.isEmpty(filePath)) {
System.out.println("参数不能为空")
resStr = "参数不能为空";
}else{
try {
String fileCode = encodeBase64FromFile(filePath);
resStr = fileCode ;
} catch (Exception e) {
e.printStackTrace();
}
}
return resStr ;
}
/**
* 文件转成base64 字符串
*/
private String encodeBase64FromFile(){
String encodeContents=null;
FileInputStream fin =null;
BufferedInputStream bin =null;
ByteArrayOutputStream baos = null;
BufferedOutputStream bout =null;
try {
fin = new FileInputStream(new File(path));
bin = new BufferedInputStream(fin);
baos = new ByteArrayOutputStream();
bout = new BufferedOutputStream(baos);
byte[] buffer = new byte[1024];
int len = bin.read(buffer);
while(len != -1){
bout.write(buffer, 0, len);
len = bin.read(buffer);
}
bout.flush();
byte[] bytes = baos.toByteArray();
encodeContents= Base64.encodeBase64String(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
fin.close();
bin.close();
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return encodeContents;
}
服务器B
/**
* 从服务器A上获取文件
* @param filePath
* @return
*/
@RequestMapping(value="/getfileByNameFromA")
public String getfileByNameFromA(@RequestParam(value = "filePath") String filePath){
String res = "";
//这部分是发起请求,根据自己的情况写。RestTemplateUtil可以使用spring mvc 内置的代替。
Map<String ,Object> param = new HashMap<String,Object>();
param.put("filePath",filePath);
res = RestTemplateUtil.postMap("http://192.168.83.131:8000/FileApi/file/getfileByName", param);
return res;
}
服务器C
<html>
<head>
<a href="#">下载</a>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$("a").click(function () {
var type="xlsx";
$.ajax({ url:"http://192.168.83.132:8000/FileApi/file/getfileByNameFromA",//
method:"post",
data:{
"filePath":"/u01/ntc/app/zhihuinsApi/log/test."+type,
"fileName":"test."+type
},
success:function (res) {
if(res){
//res为Base64字符串
downloadFileByBase64(res, 'image/png', "test."+type);
},error:function (e) {
console.log(e)
}
})
});
/**封装blob对象*/
function dataURLtoBlob(base64Str, mimeTypeStr) {
var bstr = atob(base64Str), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mimeTypeStr });
}
/**创建一个a标签,并做下载点击事件*/
function downloadFile(hrefUrl,fileName){
var a = document.createElement("a")
a.setAttribute("href",hrefUrl)
a.setAttribute("download",fileName)
a.setAttribute("target","_blank")
let clickEvent = document.createEvent("MouseEvents");
clickEvent.initEvent("click", true, true);
a.dispatchEvent(clickEvent);
}
/**下载文件的方法*/
function downloadFileByBase64(base64Str, mimeTypeStr, fileName){
var myBlob = new Blob([u8arr], { type: mimeTypeStr })
dataURLtoBlob(base64Str, mimeTypeStr)
var myUrl = URL.createObjectURL(myBlob)
downloadFile(myUrl,fileName)
}
</script>