/**
* @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文件当我尝试打开该下载文件时,由于文件格式或文件扩展名为无效。请帮我解决这个问题。提前谢谢。
答案 0 :(得分:1)
替换此行:
PrintWriter out = response.getWriter();
这一行:
OutputStream out = response.getOutputStream();
您正在从InputStream中读取一个字节,您应该再次向OutputStream写入一个字节来复制它。现在你的字节作为字符发送到PrintWriter,这是错误的。
并删除此行:
System.out.println("Buffer Reader length :"+fileInputStream.read());
此行正在读取文件中的第一个字节并将其丢弃,因此下载的文件缺少其第一个字节。