La descarga también es un tema común, a veces descargamos el pdf y lo abrimos directamente, o la ofd descargada es un paquete comprimido. Hay una situación a la que se enfrenta este problema hoy que provocará esta situación.
- Pseudocódigo para apertura directa
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();
}
}
- el problema radica en
El problema : De hecho, no es difícil encontrar que el código parece no ser un problema, pero al configurar el atributo de respuesta, outputStream = response.getOutputStream (); no se ha configurado cuando se obtiene el flujo de salida, lo que hace que función de atributo para que ya no se refleje en el flujo de salida. Al conocer el problema, sabemos que nuestra configuración debe establecerse antes de obtener el flujo de salida.
- Pseudocódigo final
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();
}
}