Export data-list in excel (running a post ajax request): how retrieve the file?

cancel
Showing results for 
Search instead for 
Did you mean: 
zlucy82
Active Member II

Export data-list in excel (running a post ajax request): how retrieve the file?

Jump to solution

Hi all,

i have implemented a function that exports site data-list informations in a excel file, but i have a problem to retrieve the file.

To do this, i've followed the tutorial of KRUTIK JAYSWAL: http://www.krutikjayswal.com/2017/07/alfresco-webscript-export-data-in-excel.html.

The difference with its code is that i don't run a redirect to call the webscript (window.location.href = Alfresco.constants.PROXY_URI+"export/excel/?nodeRef="+file.nodeRefSmiley Wink but i need send a json object to the java controller of the webscript.

I've performed an ajax post request to send informations through a webscript that extends the AbstractWebScript webscript type. The java controller class processes the json object and writes the response ( file excel) in the WebScriptResponse object (incomplete function).

Now, i dont't know how get back the file because the webscript returns an incomprensible response.

The javascript function that runs the post request is this:

Alfresco.util.Ajax.request({
      url: Alfresco.constants.PROXY_URI + "export/data/post",
      method: Alfresco.util.Ajax.POST,
      dataObj:
                {
                  site: this.options.siteId,
                  fileName: "report-" + today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate()
                  + '-' + today.getHours() + '-' + today.getMinutes() + '-' + today.getSeconds(),
                  rows: req                 
                },
      requestContentType: Alfresco.util.Ajax.JSON,
      successMessage: "Successfully retrieved the Hierarchy.",
      successCallback: {
          fn: function(response){
                alert(response.serverResponse.responseText);
               },
          scope:this
      },
      failureMessage: "Failed to retrieved the Hierarchy!",
      failureCallback: {
          fn: function(response){},
          scope:this
      },
      execScripts: true
});

The webscript's descriptor is this:

<webscript>
  <shortname>Export to Excel Webscript</shortname>
  <description>Sample Export to excel webscript</description>
  <url>/export/data/post</url>
  <format default="xls">argument</format>
  <authentication>user</authentication>
  <transaction allow="readonly">required</transaction>
</webscript>

The java class of the webscript's controller is this:

/**
* A java class controller of export data in excel
*
*/

public class ExportDataExcel extends AbstractWebScript {
     private String fileName = "ExcelSheet";
     private String format = "xlsx";
    
     //logging
      Log log = LogFactory.getLog(ExportDataExcel.class);

      /**
       * This method is inherited from AbstractWebscript class and called
       * internally.
       */

      @Override
      public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException{
     
           String nomeSito = "";
           String nomeFile = "";
           
           
           //Controlliamo che la richiesta non sia vuota
           if (req.getContent() == null)
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Corpo del POST assente.");           
         
         JSONObject datiExcel = null;
          
          //check json object
          Object jsonO = req.parseContent();
          if (jsonO instanceof JSONObject && jsonO != null)
               datiExcel = (JSONObject)jsonO;
          else
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "JSON errato " + jsonO);
       
       
       
           try{
               //si dovrebbe controllare che sia un JSON valido
               Map<String, Object> map = new HashMap<String, Object>();
               Iterator<String> keyItr = datiExcel.keys();
               while(keyItr.hasNext()) {
                    String key = keyItr.next();
                    log.debug(key);
                    if(key.equals("site")) nomeSito = datiExcel.getString(key);
                    if(key.equals("fileName")) nomeFile = datiExcel.getString(key);
                    if(key.equals("rows")){
                         // TO DO ...
                    
                    }
                   map.put(key, datiExcel.getString(key));
               }
               
          }
          catch (JSONException e) {
              throw new RuntimeException(e);
          }
          
          
          //TO DO: pass the json object information to process them
          writeDataInExcel(res);
           
      }
      .....
1 Solution

Accepted Solutions
zlucy82
Active Member II

Re: Export data-list in excel (running a post ajax request): how retrieve the file?

Jump to solution

Hi Krutik, thank you for your response. I have modified my javascript function following your indications and now it works. This is my new code.

   var json = JSON.stringify( {
            site: this.options.siteId,
            fileName: titleDatalist +"."+ today.getFullYear() + '.' + (today.getMonth()+1) + '.' + today.getDate()
                       + '-' + today.getHours() + '.' + today.getMinutes() + '.' + today.getSeconds();,
            columns: labels,
            rows: req
         } );


   var req = new XMLHttpRequest();
   req.open("POST", Alfresco.constants.PROXY_URI + "export/data/post", true);    
   req.setRequestHeader('Content-Type', 'application/json');
   req.responseType = "blob";    
   req.onload = function(e) {
     if (this.status === 200) {
        var blob = this.response;
        var filename = "ExportExcelDataList.xlsx";
        var downloadLink = window.document.createElement('a');
        var contentTypeHeader = req.getResponseHeader("Content-Type");
        downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader }));
        downloadLink.download = filename;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        }
     };
   req.send(json);
          

Thank you very much!

View solution in original post

2 Replies
krutik_jayswal
Senior Member II

Re: Export data-list in excel (running a post ajax request): how retrieve the file?

Jump to solution

If i understood correctly, you would like to download a file by making an ajax request.There are some complexity in it.

But below code may help you.

function downloadFile(urlToSend) {     var req = new XMLHttpRequest();     req.open("GET", urlToSend, true);     req.responseType = "blob";     req.onload = function (event) {         var blob = req.response;         var fileName = req.getResponseHeader("fileName") //if you have the fileName header available         var link=document.createElement('a');         link.href=window.URL.createObjectURL(blob);         link.download=fileName;         link.click();     };      req.send(); }

This is created in a pure java script but in think you will find some way , how you can use it in YUI.

For more details on this you can refer below link..

javascript - download file using an ajax request - Stack Overflow 

zlucy82
Active Member II

Re: Export data-list in excel (running a post ajax request): how retrieve the file?

Jump to solution

Hi Krutik, thank you for your response. I have modified my javascript function following your indications and now it works. This is my new code.

   var json = JSON.stringify( {
            site: this.options.siteId,
            fileName: titleDatalist +"."+ today.getFullYear() + '.' + (today.getMonth()+1) + '.' + today.getDate()
                       + '-' + today.getHours() + '.' + today.getMinutes() + '.' + today.getSeconds();,
            columns: labels,
            rows: req
         } );


   var req = new XMLHttpRequest();
   req.open("POST", Alfresco.constants.PROXY_URI + "export/data/post", true);    
   req.setRequestHeader('Content-Type', 'application/json');
   req.responseType = "blob";    
   req.onload = function(e) {
     if (this.status === 200) {
        var blob = this.response;
        var filename = "ExportExcelDataList.xlsx";
        var downloadLink = window.document.createElement('a');
        var contentTypeHeader = req.getResponseHeader("Content-Type");
        downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader }));
        downloadLink.download = filename;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        }
     };
   req.send(json);
          

Thank you very much!