如何为使用 JSP 生成的下载文件显示“保存文件”对话框
How can I present a "save file" dialog box for a downloaded file generated using JSP?
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet(seldate+"|"+seldate2);
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("NUMBER");
rowhead.createCell((short) 1).setCellValue("EMPLOYEE NAME");
rowhead.createCell((short) 2).setCellValue("ITEM QUANTITY");
rowhead.createCell((short) 3).setCellValue("AMOUNT PAID");
//rowhead.createCell((short) 4).setCellValue("");
String sql="something";
ResultSet rs=st.executeQuery(sql);
ResultSetMetaData rsmd=null;
rsmd=rs.getMetaData();
int colcnt=rsmd.getColumnCount();
int i=1;
double grandTotal = 0.0;
while(rs.next())
{
/*----*/
String [] dot=new String[colcnt];
//System.out.println("'n record count for data :"+(++tr));
for (int jk=1;jk<=colcnt;jk++)
{
dot[jk-1]=rs.getString( jk);
}
al.add(dot);
}
String pot []=null;
//HSSFRow row= sheet.createRow((short)i);
for(int mn=0;mn<al.size();mn++)
{
pot=(String[])al.get(mn);
String number=pot[0];
String empname=pot[1];
String itemqty=pot[2];
String emprate=pot[3];
double Rate=Double.parseDouble(emprate);
//out.println(Rate);
int Qty=Integer.parseInt(itemqty);
//out.println(Rate);
totAmt=(Rate)*(Qty);
grandTotal += totAmt;
/*----*/
HSSFRow row= sheet.createRow((short)i);
//row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("BID")));
row.createCell((short) 0).setCellValue(number);
row.createCell((short) 1).setCellValue(empname);
row.createCell((short) 2).setCellValue(itemqty);
row.createCell((short) 3).setCellValue(totAmt);
//row.createCell((short) 4).setCellValue(rs.getString(""));
i++;
//row.createCell((short)3).setCellValue("12345");
}
/*--------------------------*/
HSSFRow row1=sheet.createRow((short)i);
row1.createCell((short) 2).setCellValue("Grand Total");
row1.createCell((short) 3).setCellValue(grandTotal);
/*---------------------------*/
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
//out.println("<script>win=window.open('ExcelMsg.jsp','popup','toolbar=no,status=no,height=300,width=800');</script>");
我有上面的代码,它在执行时生成一个存储在客户端的 Excel 文件,直接发送到名为"report"的目录中的"D"驱动器。我希望通过用户选择发生这种情况意味着它必须打开一个文件对话框(保存对话框(并让用户指定他想要存储 Excel 文件的位置。如何做到这一点?
更新的代码
<%
ArrayList al=new ArrayList();
int tr=0;
double totAmt=0.0;
try
{
String seldate=request.getParameter("Sdate");
out.println("'n selected date : :"+seldate);
String seldate2=request.getParameter("Sdate2");
out.println("'n selected date 2 : :"+seldate2);
String str_date=seldate2;
SimpleDateFormat formatter ;
Date date =new Date() ;
Calendar cal2=Calendar.getInstance();
formatter = new SimpleDateFormat("dd-MMM-yyyy");
//date = (Date)formatter.parse(str_date);
cal2.setTime(formatter.parse(str_date));
cal2.add(Calendar.DATE,1);
str_date=formatter.format(cal2.getTime());
out.println("'n Today is " +str_date );
Calendar cal = new GregorianCalendar();
String name=cal.get(Calendar.DATE) +"-" +(cal.get(Calendar.MONTH)+1) + "-"+cal.get(Calendar.YEAR);
/*-------------------------------------------------------------------------------------------------*/
System.out.println("1");
String fileStoreURL="";
String rootpath="D:";
fileStoreURL =rootpath+"/Report";
System.out.println("2");
try {
File f = new File(fileStoreURL);
if (!f.exists())
{
f.mkdirs();
}
}
catch (Exception e)
{
}
System.out.println("3");
String filename=fileStoreURL+"/"+name+".xls" ;
//String filename=name+".xls" ;
System.out.println("4");
/*-------------------------------------------------------------------------------------------------*/
System.out.println("5");
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet(seldate+"|"+seldate2);
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("NUMBER");
rowhead.createCell((short) 1).setCellValue("EMPLOYEE NAME");
rowhead.createCell((short) 2).setCellValue("ITEM QUANTITY");
rowhead.createCell((short) 3).setCellValue("AMOUNT PAID");
//rowhead.createCell((short) 4).setCellValue("");
String sql="something";
ResultSet rs=st.executeQuery(sql);
ResultSetMetaData rsmd=null;
rsmd=rs.getMetaData();
int colcnt=rsmd.getColumnCount();
int i=1;
double grandTotal = 0.0;
while(rs.next())
{
/*----*/
String [] dot=new String[colcnt];
//System.out.println("'n record count for data :"+(++tr));
for (int jk=1;jk<=colcnt;jk++)
{
dot[jk-1]=rs.getString( jk);
}
al.add(dot);
}
String pot []=null;
//HSSFRow row= sheet.createRow((short)i);
for(int mn=0;mn<al.size();mn++)
{
pot=(String[])al.get(mn);
String number=pot[0];
String empname=pot[1];
String itemqty=pot[2];
String emprate=pot[3];
double Rate=Double.parseDouble(emprate);
//out.println(Rate);
int Qty=Integer.parseInt(itemqty);
//out.println(Rate);
totAmt=(Rate)*(Qty);
grandTotal += totAmt;
/*----*/
HSSFRow row= sheet.createRow((short)i);
//row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("BID")));
row.createCell((short) 0).setCellValue(number);
row.createCell((short) 1).setCellValue(empname);
row.createCell((short) 2).setCellValue(itemqty);
row.createCell((short) 3).setCellValue(totAmt);
//row.createCell((short) 4).setCellValue(rs.getString(""));
i++;
//row.createCell((short)3).setCellValue("12345");
}
/*--------------------------*/
HSSFRow row1=sheet.createRow((short)i);
row1.createCell((short) 2).setCellValue("Grand Total");
row1.createCell((short) 3).setCellValue(grandTotal);
/*---------------------------*/
response.setHeader("Content-Length", String.valueOf(filename.length())); response.setHeader("Content-Disposition", "attachment; filename='"" + filename + "'"");
InputStream input = new BufferedInputStream(new FileInputStream(filename), 1024 * 10);
OutputStream output = new BufferedOutputStream(response.getOutputStream(), 1024 * 10);
byte[] buffer = new byte[1024 * 10];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
错误:
java.io.FileNotFoundException: 1-8-2012.xls (The system cannot find the file spe
cified)
java.io.FileNotFoundException: 1-8-2012.xls (The system cannot find the file spe
cified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at org.apache.jsp.sapep.elrservices.processor.ExcelReport2_jsp._jspServi
ce(ExcelReport2_jsp.java:238)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper
.java:377)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:3
13)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java
:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.proce
ss(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:48
9)
at java.lang.Thread.run(Unknown Source)
您需要将
File
的内容写入ServletOutputStream
,除此之外,您还需要设置响应的content-length
和content-disposition
,
下面是一个简单的示例:
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename='"" + fileName + "'"");
InputStream input = new BufferedInputStream(new FileInputStream(file), 1024 * 10);
OutputStream output = new BufferedOutputStream(response.getOutputStream(), 1024 * 10);
byte[] buffer = new byte[1024 * 10];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
显然,您还需要添加适当的异常处理代码。
您需要将
文件的内容写入 ServletOutputStream,除此之外,您还需要设置响应的内容长度和内容处置,如上答案所示。
来到"另存为"你需要做如下的事情,
转到浏览器设置并将默认下载位置更改为下载前询问每个文件的保存位置。
对于谷歌浏览器,
转到 :- 设置> 显示高级设置>下载。 勾选复选框 下载前询问每个文件的保存位置。
相关文章:
- 如何将旋转的画布元素保存到文件中
- 使用ImageMagick生成图像而不保存到文件,但仍在网站上显示
- 将Javascript从PHP变量保存到文件
- 如何使用html / angularjs保存图像文件
- 将从 URL 输出的 JSON 保存到文件 javascript
- 将图像输出到浏览器,然后再将其保存到文件夹
- 保存HTML文件后,Javascript不起作用
- 从图像URL javascript html保存图像文件
- 读取一个本地文件,编码为base64,我想给用户一个将结果保存到文件的选项
- 在jspdf中使用addHTML保存pdf文件失败
- 如何用我在HTML5画布上绘制的src保存图像文件
- 允许用户键入html标签并将其保存到文件中以在网站上显示
- 保存对文件的更改而不重新加载页面
- Javascript FileSaver在写入大量文件后保存空文件
- CSSLint:如何将控制台日志中的日志保存到文件中
- imacros提取两部分数据+连接常量保存到文件javascript
- 将要保存的文件传递到php
- 在IE8中使用“另存为”execCommand以ANSI格式而不是UCS2-Little Endian保存XML文件
- Javascript -- 如何使用 HTA 保存 txt 文件
- 使用javascript保存XHR文件