在我的应用程序中,我可以选择从用户下载文件夹中的excel文件,所有功能都运行良好,但它只显示控制台中的响应,我无法同时下载excel文件浏览器不显示保存或下载选项。
注意:我使用了所有可能的 ContentType(“application / vnd.openxmlformats officedocument.spreadsheetml.sheet”)。
String downloadFolder = request.getRealPath(fileDetail.getFilePath()+fileDetail.getFileName());
Path file = Paths.get(downloadFolder);
if(Files.exists(file)){
response.reset();
response.setContentType("application/vnd.openxmlformats officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=\"Demo.xlsx");
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e){
return null;
}
}
我该如何解决这个问题?我需要在调用方法时下载excel文件。谢谢
答案 0 :(得分:0)
尝试下载文件
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-disposition","attachment; filename=check.xlsx"); // Used to name the download file and its format
File my_file = new File("E://outputtext.xlsx"); // We are downloading .xlsx file, in the format of doc with name check - check.xlsx
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
答案 1 :(得分:0)
我猜是因为在连续步骤中调用了flush()。它无法正常工作。
尝试使用finally块来刷新..
答案 2 :(得分:0)
您可以尝试按以下方式编写文件
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
//将字节从源复制到目标(本例中为outputstream),关闭两个流。
FileCopyUtils.copy(inputStream,response.getOutputStream());