/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hi inside download file :");
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
String filename = "ResetPassword.xlsx";
InputStream is = null;
//is = this.getClass().getClassLoader().getResourceAsStream("LoginConfigurations.xlsx");
//System.out.println("InputStream :"+is);
String filepath = "E:\\SPACE_OM_01.02\\SPACE-OM_1.0-V01.02\\WebContent\\Data\\";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
// use inline if you want to view the content in browser, helpful for
// pdf file
response.setHeader("Content-Disposition","inline; filename=\"" +filename + "\"");
FileInputStream fileInputStream = new FileInputStream(filepath+ filename);
/*BufferedReader br = new BufferedReader(new InputStreamReader(is));
int line;
System.out.println("Buffer Reader length :"+br.read());
StringBuilder sb = new StringBuilder();
while ((line = br.read()) != -1) {
//sb.append(line);
out.write(line);
}
br.close();*/
int line;
System.out.println("Buffer Reader length :"+fileInputStream.read());
//StringBuilder sb = new StringBuilder();
while ((line = fileInputStream.read()) != -1) {
//sb.append(line);
out.write(line);
}
fileInputStream.close();
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
我正在尝试使用按钮下载扩展名为 .xlsx 的 Excel 文件,点击下载按钮后,文件正在下载,当我尝试打开该下载文件时,出现错误,例如 Excel 文件无法打开,因为文件格式或文件扩展名无效。请帮助我解决这个问题。预先感谢。
替换此行:
PrintWriter out = response.getWriter();
用这一行:
OutputStream out = response.getOutputStream();
您正在从 InputStream 读取一个字节,并且应该再次将一个字节写入 OutputStream 以复制它。现在您的字节作为字符发送到 PrintWriter,这是错误的。
并删除这一行:
System.out.println("Buffer Reader length :"+fileInputStream.read());
此行从文件中读取第一个字节并将其丢弃,因此下载的文件丢失了第一个字节。
几天前我遇到了同样的问题,在 Maven 依赖项中添加
<nonFilteredFileExtensions>
后解决了,如下所示:
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
这将阻止二进制文件过滤。