java下载文件接口输出文件内容为空
如果不用javaresponse.getOutpuStream
,而是new一个FileOutputStream,写死为本地路径,那么输出的文件可以正常查看,一点问题没有。可是下面的代码下载的文件,如果是图片,查看的时候提示不支持,pdf格式有页数,内容是空白的,文本格式也是空白的。换过ContentType也没解决,也试过直接write读回来的字节数组也没用。并且控制台并没有报错。希望各位朋友能够指点一二,不胜感激
public void downloadAnnexFile(String annexId, HttpServletRequest request, HttpServletResponse response){
logger.info("进入service");
RDDataAnnexBO annexInfo = rdDataAnnexDao.selectAnnexInfoById(annexId);
logger.info("附件对象:" + annexInfo.toString());
if(annexInfo == null){
return;
}
//文件名转义回原文展示给用户下载
String fileName = unescapeHtml4ByString(annexInfo.getFileName());
logger.info("转义回原文的文件名:" + fileName);
ByteArrayInputStream byteArrayInputStream = null;
String downloadFileName = "";
OutputStream outputStream = null;
try {
response.setContentType("application/octet-stream");
String userAgent = request.getHeader("User-Agent");
boolean isMSIE = ((userAgent != null && userAgent.contains("MSIE")) ||
(null != userAgent && (userAgent.contains("like Gecko") && !userAgent.contains("Safari"))) ||
(userAgent != null && userAgent.contains("Edge")));
if (isMSIE) {
downloadFileName = URLEncoder.encode(fileName + annexInfo.getFileSuffix(), "UTF-8");
} else {
downloadFileName = new String((fileName + annexInfo.getFileSuffix()).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", downloadFileName));
byte[] base = hdfsBucketDubboService.readStreamFileToHdfs(annexInfo.getAnnex(), "/BLM/RD");
byteArrayInputStream = new ByteArrayInputStream(base);
outputStream = response.getOutputStream();
byte[] content = new byte[1024];
int length = 0;
while ((length = byteArrayInputStream.read(content)) != -1) {
outputStream.write(content, 0, length);
}
} catch (Exception e) {
logger.error("下载HDFS文件异常", e);
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
} catch (Exception e) {
logger.error("流关闭异常:", e);
}
}
logger.info("service完成");
}