//控制层文件下载方法
/**
* 导出文本文件返回二进制数据流* @param request
* @param response
* @param url 文件路径 此路径为文件在服务器上路径
* @param fileName 原文件名
*/
@RequestMapping(value = "/download", method = {RequestMethod.GET, RequestMethod.POST })
@ResponseBody
@ApiOperation(value = "文件下载", notes = "文件下载", code = 200, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiImplicitParams({@ApiImplicitParam(name = "url", value = "文件存放路径", paramType = "query", dataType = "string", required = true),
@ApiImplicitParam(name = "fileName", value = "原文件名", paramType = "query", dataType = "string", required = true) })
public Response<String> download(HttpServletRequest request, HttpServletResponse response, @RequestParam("url") String url,
@RequestParam("fileName") String fileName) {
Response<String> res = new Response<String>();
response.setContentType("application/x-msdownload");
OutputStream out = null;
byte[] b = null; // 存储文件流
String group_name = null;
String remote_filename = "";
logger.info("<<<<<<<<FileUploadController.download下载文件开始,文件名:{},下载路径:{}>>>>>>>>", fileName, url);
//浏览器兼容验证
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
fileName = URLEncoder.encode(fileName, "utf-8"); //ie浏览器
} else {
fileName = new String(fileName.getBytes("utf-8"), "iso8859-1"); //火狐、谷歌。。。其它未验证
}
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
// ;// 对参数进行解码
out = response.getOutputStream();
// 截取url地址获取参数group_name和remote_filename
String[] arr = url.split("//")[1].split("/");
group_name = arr[1];
for (int i = 2; i < arr.length; i++) {
remote_filename = remote_filename + arr[i] + "/";
}
remote_filename = remote_filename.substring(0, remote_filename.lastIndexOf("/"));
logger.info("<<<<<<<<group_name:{},remote_filename:{}>>>>>>>>", group_name, remote_filename);
b = FastDFSUtil.downFile(group_name, remote_filename); //此处用工具 返回二进制流
if (b == null) {
res.setCode(ReturnCodeEnum.CODE_1101.getCode());
res.setMsg("下载文件失败");
return res;
}
out.write(b); //将流交给页面处理
out.flush();
} catch (Exception e) {
res.setCode(ReturnCodeEnum.CODE_1101.getCode());
res.setMsg("下载文件异常");
logger.error("<<<<<<<<FileUploadController.download下载文件发生异常!{}>>>>>>>>", e);
return res;
}
finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.error("<<<<<<<<FileUploadController.download文件输出流关闭发生异常!{}>>>>>>>>", e);
}
}
}
try {
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
fileName = URLDecoder.decode(fileName, "utf-8");
} else {
fileName = new String(fileName.getBytes("iso8859-1"), "utf-8");
}
logger.info("<<<<<<<<FileUploadController.download下载文件{}成功>>>>>>>>", fileName);
} catch (UnsupportedEncodingException e) {
logger.error("<<<<<<<<FileUploadController.download文件下载解析异常>>>>>>>>>");
e.printStackTrace();
}
return res;
}
//服务层返回二进制方法
/**
* 方法描述:文件下载* @param group_name
* @param remote_filename
* @return 保存文件到服务器
*/
public static byte[] downFile(String group_name, String remote_filename) {
StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
byte[] b = null;
try {
b = storageClient1.download_file(group_name, remote_filename);
return b;
} catch (IOException | MyException e) {
logger.error("<<<<<<<<<<<<<<<FastDFSUtil.downFile文件下载发生异常{}>>>>>>>>>>>>>>>", e);
}
return b;
}
/**
*
* 前端页面不能用ajax 我用的form提交方式。同时对url地址做了编码
*/
function appendFile(fileName,fileUrl,taskId){ var html = '<div class="row col-xs-12">'; html += '<input type="hidden" name="files" value="'+fileName+'#;'+fileUrl+'#;'+taskId+'"/>'; html += '<a target="_blank" href="javascript:void(0)" οnclick="fileDownload(\''+fileUrl+'\',\''+fileName+'\');return false;">'+fileName+'</a> '; html += '<button class="btn btn-minier btn-warning" οnclick="delFile(this)">' + ' <i class="ace-icon fa fa-trash-o bigger-110"></i>' + ' <span class="bigger-110 no-text-shadow">删除</span>' + ' </button>'; html += '</div>'; $('#uploadFiles').append(html); } function fileDownload(url,fileName) { fileName = encodeURIComponent(fileName);//对参数进行编码操作防止特殊字符出现400错误提示 var param = 'url=' + url + '&fileName=' + fileName; exportFile(api.file.filedownload,param); }
function exportFile(url,param){ var tempUrl = url + '?'+ param; var form = $("<form>"); form.attr('style', 'display:none'); form.attr('target', ''); form.attr('method', 'post'); form.attr('action', tempUrl); var token = localStorage.getItem('OaAuthorizationToken'); var userId = localStorage.getItem('userid'); var input1 = $('<input>').attr('type', 'hidden').attr('name', 'AuthorizationToken').attr('value', token); var input2 = $('<input>').attr('type', 'hidden').attr('name', 'authorizationUserId').attr('value', userId); $('body').append(form); form.append(input1); form.append(input2); form.submit(); form.remove(); }
之前遇到下载文档有空格或者特殊字符问题都是因为前端页面没有对参数进行编码。。
fileName = encodeURIComponent(fileName);//对参数进行编码操作防止特殊字符出现400错误提示
后台也需要处理
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
fileName = URLEncoder.encode(fileName, "utf-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
}
先谢谢网上大神些的参考文献。。
首次发文。。都是直接提的自己代码。。记录下工作遇到的问题。。