Java 如何通过设置内容类型使用.xlsx保存文件
下面给出的代码在jsp中尝试。下面的代码在中打开窗口资源管理器以将文件保存到.xlsx(使用chrome浏览器),但要求在单击图标时自动下载文件。尝试了堆栈溢出中发布的类似问题的解决方案,但找不到该问题的正确解决方案 在浏览器Firefox和chrome中检查解决方案Java 如何通过设置内容类型使用.xlsx保存文件,java,jsp,Java,Jsp,下面给出的代码在jsp中尝试。下面的代码在中打开窗口资源管理器以将文件保存到.xlsx(使用chrome浏览器),但要求在单击图标时自动下载文件。尝试了堆栈溢出中发布的类似问题的解决方案,但找不到该问题的正确解决方案 在浏览器Firefox和chrome中检查解决方案 <%@ taglib uri="/struts-tags" prefix="s"%> <% response.setContentType("application/application/vnd.ope
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
response.setContentType("application/application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet");
response.setHeader ("Content-Disposition",
"attachment;fileName=tempAuthorizationCloseOutReportsResult.xlsx;");
%>
<s:set var="resultList" value="#request.tempAuthorizationCloseoutResult" />
<div>
<h3></h3>
</div>
<br/>
<s:if test="#resultList.size <= 0">
<table>
<tr>
<td>
<b> <s:text name="ui.label.text.norecordsfound" /> </b>
</td>
</tr>
</table>
</s:if>
<s:elseif test="#resultList.size> 0">
<table>
<tr>
<td>
<b><s:text name="ui.label.text.totalnumberofrecordsfound"/> :
<s:property value="#resultList.size" /> </b>
</td>
</tr>
</table>
:
@覆盖
受保护的void doPost(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
response.setContentType(“application/vnd.openxmlformats of cedocument.spreadsheetml.sheet;charset=UTF-8”);
文件xfile=
try(BufferedOutputStream bfos=new BufferedOutputStream(response.getOutputStream());
FileInputStream fs=新的FileInputStream(xfile)){
字节[]缓冲区=新字节[fis.available()];
fs.read(缓冲区);
写(buffer,0,buffer.length);
bfos.flush();
}
}
浏览器可以随心所欲。服务器无法告诉它自动将其保存到任何位置。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
File xfile = < File>
try (BufferedOutputStream bfos = new BufferedOutputStream(response.getOutputStream());
FileInputStream fs = new FileInputStream(xfile)) {
byte[] buffer = new byte[fis.available()];
fs.read(buffer);
bfos.write(buffer, 0, buffer.length);
bfos.flush();
}
}