下载也是老生常谈的话题 有时候我们下载的比如pdf 直接打开,或者下载的ofd 是一个压缩包。今天正对这个问题 有一种情况会导致这种情况。
- 直接打开的伪代码
StringBuilder fileName = new StringBuilder();//模拟文件名称
fileName.append(queryByInvoiceId.getInvoiceCode()).append("_").append(queryByInvoiceId.getInvoiceNum()).append(suf);
OSSClient ossClient = null;
InputStream inputStream = null;
String key = null;
ServletOutputStream outputStream = null;
ossClient = AliyunOSSClientUtil.getOSSClient();
String key = "aliyunkey";
inputStream = GetInputStream(ossClient, key);
try {
outputStream = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[4096];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
outputStream.flush();
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");//设置下载类型
response.addHeader("Content-Disposition",
"attachment;filename=" + fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(),e);
}finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
- 问题所在
问题所在:其实不难发现代码看似是没有问题,但是在设置response 属性的时候 在 outputStream = response.getOutputStream();获取输出流的时候 还没有设置,导致属性作用不会再输出流体现。知道问题所在 我们就知道我们设置应该是在获取输出流之前设置。
- 最终伪代码
StringBuilder fileName = new StringBuilder();
OSSClient ossClient = null;
InputStream inputStream = null;
String key = null;
ServletOutputStream outputStream = null;
ossClient = AliyunOSSClientUtil.getOSSClient();
String key = "aliyunKey";
inputStream = GetInputStream(ossClient, key);
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition",
"attachment;filename=" + fileName);
outputStream = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[4096];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
outputStream.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(),e);
}finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}