针对微服务通用文件下载接口
文件下载接口
/**
* @param affixFileUrl 文件下载地址
* @param affixFileName 文件名
* @param response
* @param request
* @return
*/
@ApiOperation(value = "下载", notes = "下载附件")
@RequestMapping(value = "/downloadAffix", method = RequestMethod.GET)
public Result downloadAffix(@RequestParam(value = "affixFileUrl", required = true) String affixFileUrl,
@RequestParam(value = "affixFileName", required = true) String affixFileName,
HttpServletResponse response, HttpServletRequest request) {
Result<?> result = new Result<>();
BufferedInputStream bis = null;
OutputStream os = null;
try {
String userAgent = request.getHeader("User-Agent");
//解决下载时文件名乱码问题
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
affixFileName = java.net.URLEncoder.encode(affixFileName, "UTF-8");
} else {
// 非IE浏览器的处理:
affixFileName = new String(affixFileName.getBytes("UTF-8"), "ISO-8859-1");
}
FileUtils fileUtils=new FileUtils();
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + affixFileName);
byte[] buff = new byte[1024];
//因需要这里截掉了服务名,非必须
affixFileUrl = affixFileUrl.replace("/"+ftpUtil.getServerName()+"/","");
//文件路径拼接
String filePath= fileUtils.getFilePath()+affixFileUrl;
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
}catch (Exception e){
log.error(e.getMessage());
return Result.error(-1, e.getMessage());
}finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("下载附件成功:");
return result.success("下载成功");
FileUtils中的方法
/**
* 获取文件当前路径
* @return
*/
public String getFilePath(){
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attr.getRequest();
String filePath=request.getSession().getServletContext().getRealPath("/");
return filePath;
}
前端使用js调用
//下载附件
function downloadAffix(affixFileUrl,affixFileName) {
window.location.href = '/file-server'+'/gjpxfile/downloadAffix?affixFileUrl=' + affixFileUrl+'&affixFileName='+affixFileName;
}