多服务器之间文件转成Base64编码后,前端通过返回的编码转换成为文件下载。

前景:
最近开发中有这样一个场景
服务器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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张帅三代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值