gpt4 book ai didi

java - 通过 Servlet 下载 Excel 文件

转载 作者:行者123 更新时间:2023-12-01 09:45:53 24 4
gpt4 key购买 nike

我正在使用通过ajax调用调用的以下代码来创建我的Excel文件。单击下载按钮,Excel文件将在根位置生成。但我无法看到用户保存/另存为文件的提示。我可以看到浏览器的响应选项卡,其中包含 Excel 的内容。但我希望出现“另存为”对话框选项。下面的代码是否有任何修正可以解决这个问题?

            final Date date = new Date();
final String generateDate= new SimpleDateFormat("yyyy-MM-dd").format(date);
final String filename = form_name+"-extraction-"+generateDate.toString()+".xls";
final FileOutputStream fileOutputStream = new FileOutputStream(filename);
workbook.write(fileOutputStream);
downloadFile(filename, response);

以下是下载文件方法:

private void downloadFile(final String fileName, final SlingHttpServletResponse response){
try {
final File f = new File(fileName);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "inline; filename="+fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
final int size = 1024;
try {
response.setContentLength(fin.available());
final byte[] buffer = new byte[size];
ServletOutputStream os = null;

os = response.getOutputStream();
int length = 0;
while ((length = fin.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
fin.close();
os.flush();
os.close();
} catch (final IOException e) {
e.printStackTrace();
}
}catch (final Exception ex){
LOGGER.error("ERROR IS ::: {}",ex.getMessage());
}

最佳答案

If the disposition type matches "attachment" (case-insensitively),this indicates that the recipient should prompt the user to save the
response locally, rather than process it normally (as per its media
type).

On the other hand, if it matches "inline" (case-insensitively),this implies default processing. Therefore, the disposition type"inline" is only useful when it is augmented with additionalparameters, such as the filename (see below).

Unknown or unhandled disposition types SHOULD be handled by
recipients the same way as "attachment" (see also [RFC2183],
Section 2.8).

因此,您强制浏览器显示该文件,而不是使用您的浏览器下载该文件

response.setHeader("Content-Disposition", "inline; filename="+fileName);

打电话。您应该使用“附件”而不是“内联”。

response.setHeader("Content-Disposition", "attachment; filename="+fileName);

阅读Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)了解更多信息。

关于java - 通过 Servlet 下载 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032175/

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