简体   繁体   中英

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>");

I have the above code which on executing generates an Excel file stored on the client side, directly to "D" drive in a directory named "report." That I want this to happen by user choice means it must open a file dialog box (save dialog box) and let the user specify where he wants to store the Excel file. How this can be done?

UPDATED CODE

<%
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();

ERROR:

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)

You need to write the contents of the File to the ServletOutputStream , in addition to that you need to set the content-length and content-disposition of the response,

Here is a simple example:

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();

Obviously, you will also need to add the proper exception handling code.

You need to write the contents of the File to the ServletOutputStream, in addition to that you need to set the content-length and content-disposition of the response as shown above answer.

And the coming to the "Save As" You need to do something like below,

Go to your browser Settings and Change the by default download location to Ask where to save each file before downloading.

For Google Chrome,

Go To :- Settings > Show Advances Settings > Downloads. tick the check box Ask where to save each file before downloading .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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