Ajax异步文件下载

Ajax异步文件下载

SpringMVC后端返回Base64数据

 @RequestMapping(value = "/download.do")
    @ResponseBody
    public AjaxResult downloadServerCer2(int id) throws Exception {
         AjaxResult ajaxResult = AjaxResult.error();
         try {
             byte[] cerData = certService.getCerDataById(id);
             byte[] encode = Base64.encode(cerData);
             ajaxResult = AjaxResult.ok(new String(encode,"UTF-8"));
         } catch (Exception e) {
             logger.error("#CertController@downloadServerCer error", e);
         }
         return ajaxResult;
    }

前端Vue-Resource/Ajax

this.$http.post(serverUrl+"cert/download.do",{
                    "id":id
                }).then(function(res){
                	console.log(res);
                	var blob = new Blob([res.data.message])
                    var reader = new FileReader();
                	reader.readAsDataURL(blob);
                	reader.onload = function (e) {
	                    var a = document.createElement('a');
	                    a.download = 'serverCert.cer';
	                    a.href = e.target.result;
	                    $("body").append(a);
	                    a.click();
	                    $(a).remove();
                	}
                },function(res){
                    console.log(res);
                });

你可能感兴趣的:(Spring全家桶)