0

I want to create an Excel File, if the user pressed a formular button on my webpage. My first solution works fine. The User pressed the button, the serverside java code creates the file and after the java code was executed the webbrowser open a dialog, which aks the user whether to show or to save the excel file.

But I get some new requirements from my customer. If the user pressed the formular button, it is necessary to show a animated gif image while the server side java code was executed and the animated gif must be disapeared immediately, if the server side java code was finished.

This is the Struts2 submit Button, which starts the HTTP Request, if the button was pressed:

<s:submit value="show Data" onclick="myJsFunction(); return false;" />

This is the client code, which creates and sends the HTTP Request to my Struts2 Actionclass:

function myJsFunction(){
     $.ajax({
              type: "POST",
              dataType: 'binary',
              url: "myActionClass.action",
              data: {//some necessary input values},                         
              success: function(data){                                   
                          console.log(data);
                          // js code to disappeared the animated gif image                          
                       }
      });               
 }

This is the Java code, which create the Binarycode:

private void returnExcelFileAsStream(final String filename) throws IOException {
    final InputStream is = new FileInputStream(filename);
    OutputStream os = null;
    try {
        response.setContentType("application/pdf");         
        response.setHeader("Cache-Control", "maxage=3600");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");         
        os = response.getOutputStream();
        int len;
        byte buf[] = new byte[1024];
        while ((len = is.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        is.close();
        os.close();
     }
     catch(Exception e){
         // some exeception handling
     }
}

This is the Struts2 execute method, which called the method returnExcelFileAsStream.

public String execute(){

    // some Java code
    returnExcelFileAsStream("MyExcelFile.xlsx")

    return null;
}

This is my struts.xml file:

<action name="myActionClass" class="myPackage.myActionClass">
        <result name="input" type="redirectAction">/WEB-INF/base/jsp/myJspPage.jsp</result>
</action>

Now a have the problem, that the webbrowser doesn´t open a user dialog, which asked the user to show or to save the file. With firebug I see some cryptical characters in the HTTP Response. How can I solve this problem?

  • Possible duplicate of [Download a file by jQuery.Ajax](http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) – Aleksandr M Jan 27 '16 at 09:53

2 Answers2

0

I did it like this way.

Action:

public String export() throws Exception {

HttpServletResponse response = ServletActionContext.getResponse();

List<FrontProjectList> dataList = projectApplyBaseService

.query_ProjectApply3(pqc, 0, projectApplyBaseService

.count_queryTotalProject_consumption(pqc) + 1);

HSSFWorkbook workbook = exportExcel(dataList);

ByteArrayOutputStream output = new ByteArrayOutputStream();

workbook.write(output);

byte[] ba = output.toByteArray();

excelFile = new ByteArrayInputStream(ba);

output.flush();

output.close();

return "excel";
}

Struts.xml

            <param name="contentType">application/vnd.ms-excel</param>  

            <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>  

            <param name="bufferSize">1024</param>

            <param name="inputName">excelFile</param>  

        </result>  
Tiger
  • 18
  • 4
0

I don't see any action in your JavaScript success function to trigger the browser to navigate through the newly created Excel file. I am sorry if you told about that in you text but I missed it, but I usually do it in that way:

  • My server side creates new XLS or CSV file into a location (folder, like /files) which only temporary Excel or CSV files exist in it. My server side function only returns the name of that newly created file
  • On success method of ajax, I simply execute the following:

    document.location='files/[the newly generated file's name].xls';

Then browser redirects to that file, it either displays it or ask user to download

Finally, a server side job clears this folder from 1 day old or older files

I hope this helps

  • "Then browser redirects to that file, it either displays it or ask user to download" How can I programming this, sorry but I have no idea. –  Jan 27 '16 at 09:48
  • After you execute **document.location='files/new_excel_file.xls';** fragment, browser does the rest. A typical behavior of Google Chrome should be promting for download, but an Internet Explorer on an MS Office installed computer could try to display it on browser tab. You can do nothing about it, you will just redirect to newly created file and user will somehow get it – Tolga Karanlikoglu Jan 27 '16 at 10:08
  • Do yo have an idea, how I can get filename from the data object, which is the parameter of this method in my example: success: function(data){} –  Jan 27 '16 at 11:30
  • function's data parameter can contain the value you want. You can write the fileName via response object to output in your server side, so your success function will get everything written to output as its parameter. If you need to pass more than one parameter, just combine them with a special character and split them in JavaScript side – Tolga Karanlikoglu Jan 27 '16 at 12:11
  • "You can write the fileName via response object to output in your server side, so your success function will get everything written to output as its parameter" Is it possible to give an example? I don´t understand want you mean –  Jan 27 '16 at 12:59