gpt4 book ai didi

java - 在 JAVA servlet 中下载 Excel 时出现错误文件不匹配

转载 作者:行者123 更新时间:2023-12-01 09:38:23 25 4
gpt4 key购买 nike

/**
* @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());

这一行从文件中读取第一个字节并将其丢弃,因此下载的文件丢失了第一个字节。

关于java - 在 JAVA servlet 中下载 Excel 时出现错误文件不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38650925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com