繁体   English   中英

如何为使用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-lengthcontent-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();

显然,您还需要添加适当的异常处理代码。

您还需要将File的内容写入ServletOutputStream,此外,还需要设置响应的content-length和content-disposition,如上面的答案所示。

然后进入“另存为”,您需要执行以下操作,

转到浏览器的设置,然后将默认的下载位置更改为在下载前询问每个文件的保存位置。

对于谷歌浏览器,

转到:-设置>显示高级设置>下载。 勾选复选框,在下载前询问每个文件的保存位置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM