Fórum

How to download a file from AJAX request in Liferay serveResource(-, -) met

thumbnail
Chandan Sharma, modificado 9 Anos atrás.

How to download a file from AJAX request in Liferay serveResource(-, -) met

Junior Member Postagens: 54 Data de Entrada: 04/03/14 Postagens Recentes
Hi All,

I have a requirement like: I am making an AJAX request to pass some data to my controller. In my controller I am creating a file using that data.

"Now problem is the file is not getting downloaded to client-side".

(I am using Apache POI API to create excel file from the given data). Can any one will help me to do this ?

Here is my code:

(Code to make AJAX request)


<script>
    function downloadUploadedBacklogs () {

        try {
            var table_data = [];

            var count = jQuery("#backlogTable tr:first td" ).length;
            jQuery("#<portlet:namespace/>noOfColumns").val(count);
            var index = 0;
            jQuery('tr').each(function(){

                var row_data = '';
                jQuery('td', this).each(function(){
                    row_data += jQuery(this).text() + '=';   
                });   
                table_data.push(row_data+";");

            });
            jQuery("#<portlet:namespace/>backlogDataForDownload").val(table_data);
            jQuery("#<portlet:namespace/>cmd").val("downloadUploadedBacklogs");
            alert('cmd: ' + jQuery("#<portlet:namespace/>cmd").val());  
            var formData = jQuery('#<portlet:namespace/>backlogImportForm').serialize();

            jQuery.ajax({
                url:'<%=resourceURL%>',
                data:formData,
                type: "post",
                success: function(data) {

                }
            });
            alert('form submitted');

        } catch(e) {
            alert('eroor: ' + e);
        }
    };
</script>


Java code serveResource(-,-) method


/*
*   serveResource(-, -) method to process the client request
*/
public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {


        String cmd = ParamUtil.getString(resourceRequest,"cmd");
        System.out.println("**********************cmd*************"+cmd);

        if(cmd!="") {
            if("downloadUploadedBacklogs".equalsIgnoreCase(cmd)){

                String backlogData = ParamUtil.getString(resourceRequest, "backlogDataForDownload");
                ImportBulkDataUtil.downloadUploaded("Backlogs", resourceRequest,resourceResponse);
            } 
        }
}


/ * ImportBulkDataUtil.downloadUploaded(-, -, -) method to create excel file */


public static void downloadUploaded(String schema, ResourceRequest resourceRequest,ResourceResponse resourceResponse) {

        String excelSheetName = ParamUtil.getString(resourceRequest,"excelSheetName");

        try {
            resourceResponse.setContentType("application/vnd.ms-excel");
            resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+excelSheetName+"_Template.xls");

            OutputStream outputStream=resourceResponse.getPortletOutputStream();
            //converting the POI object as excel readble object
            HSSFWorkbook objHSSFWorkbook=new HSSFWorkbook();
            HSSFSheet objHSSFSheet=objHSSFWorkbook.createSheet(excelSheetName+"_Template");

            //set the name of the workbook 
            Name name=objHSSFWorkbook.createName();
            name.setNameName(excelSheetName+"_Template");

            objHSSFSheet.autoSizeColumn((short)2);

            // create freeze pane (locking) top row
            objHSSFSheet.createFreezePane(0, 1);

            // Setting column width
            String excelData = StringPool.BLANK;
            if((schema.equalsIgnoreCase("Backlogs"))){
                System.out.println("Inside BacklogsCreation..........");
                objHSSFSheet.setColumnWidth(0, 10000);
                objHSSFSheet.setColumnWidth(1, 7000);
                objHSSFSheet.setColumnWidth(2, 7000);
                objHSSFSheet.setColumnWidth(3, 7000);
                objHSSFSheet.setColumnWidth(4, 7000);
                objHSSFSheet.setColumnWidth(5, 5000);
                objHSSFSheet.setColumnWidth(6, 5000);
                objHSSFSheet.setColumnWidth(7, 7000);
                objHSSFSheet.setColumnWidth(8, 7000);
                excelData = ParamUtil.getString(resourceRequest,"backlogDataForDownload");
            }
            System.out.println("downloadUploaded excelTableData: " + excelData);

             // Header creation logic

            HSSFRow objHSSFRowHeader = objHSSFSheet.createRow(0);
            objHSSFRowHeader.setHeightInPoints((2*objHSSFSheet.getDefaultRowHeightInPoints()));
            CellStyle objHssfCellStyleHeader = objHSSFWorkbook.createCellStyle();
            objHssfCellStyleHeader.setFillBackgroundColor((short)135);
            objHssfCellStyleHeader.setAlignment(objHssfCellStyleHeader.ALIGN_CENTER);
            objHssfCellStyleHeader.setWrapText(true);

            // Apply font styles to cell styles
            HSSFFont objHssfFontHeader = objHSSFWorkbook.createFont();
            objHssfFontHeader.setFontName("Arial");
            objHssfFontHeader.setColor(HSSFColor.WHITE.index);

            HSSFColor lightGrayHeader =  setColor(objHSSFWorkbook,(byte) 0x00, (byte)0x20,(byte) 0x60);
            objHssfCellStyleHeader.setFillForegroundColor(lightGrayHeader.getIndex());
            objHssfCellStyleHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);

            objHssfFontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            objHssfFontHeader.setFontHeightInPoints((short)12);
            objHssfCellStyleHeader.setFont(objHssfFontHeader);
            objHssfCellStyleHeader.setWrapText(true);

            // first column about Backlog title
            HSSFCell objBacklogTitleCell = objHSSFRowHeader.createCell(0);
            objBacklogTitleCell.setCellValue("Backlog");
            objBacklogTitleCell.setCellStyle(objHssfCellStyleHeader);   

            // second column about Description
            HSSFCell objBacklogDescCell = objHSSFRowHeader.createCell(1);
            objBacklogDescCell.setCellValue("Description");
            objBacklogDescCell.setCellStyle(objHssfCellStyleHeader);

            // third column about Project
            HSSFCell objProjectNameCell = objHSSFRowHeader.createCell(2);
            objProjectNameCell.setCellValue("Project");
            objProjectNameCell.setCellStyle(objHssfCellStyleHeader);
            setComment("Project which the backlog belongs to", objProjectNameCell);

            // fourth column about Category
            HSSFCell objCategoryNameCell = objHSSFRowHeader.createCell(3);
            objCategoryNameCell.setCellValue("Category");
            objCategoryNameCell.setCellStyle(objHssfCellStyleHeader);
            setComment("Category which the backlog belongs to (i.e. Bug, New Requirement, Enhancement)", objCategoryNameCell);

            // fifth column about Group
            HSSFCell objGroupNameCell = objHSSFRowHeader.createCell(4);
            objGroupNameCell.setCellValue("Group");
            objGroupNameCell.setCellStyle(objHssfCellStyleHeader);
            setComment("Group which the backlog belongs to", objGroupNameCell);

            // sixth column about Est. Start Date
            HSSFCell objEstStartDtCell = objHSSFRowHeader.createCell(5);
            objEstStartDtCell.setCellValue("Est. Start Date");
            objEstStartDtCell.setCellStyle(objHssfCellStyleHeader);
            setComment("Date Format: dd/mm/yyyy", objEstStartDtCell);

            // seventh column about Est. End Date
            HSSFCell objEstEndDtCell = objHSSFRowHeader.createCell(6);
            objEstEndDtCell.setCellValue("Est. End Date");
            objEstEndDtCell.setCellStyle(objHssfCellStyleHeader);
            setComment("Date Format: dd/mm/yyyy", objEstEndDtCell);

            // fifth column about Group
            HSSFCell objStatusCell = objHSSFRowHeader.createCell(7);
            objStatusCell.setCellValue("Status");
            objStatusCell.setCellStyle(objHssfCellStyleHeader);

            String excelTableDataRecords[] = excelData.split(";");
            for(int i=1; i<exceltabledatarecords.length; i++) { hssfrow objhssfrow="objHSSFSheet.createRow(i);" objhssfrow.setheightinpoints((2*objhssfsheet.getdefaultrowheightinpoints())); exceltabledatarecords[i]="excelTableDataRecords[i].substring(1," (exceltabledatarecords[i].length()-2)); if(exceltabledatarecords[i].charat(0)="=" ',') (exceltabledatarecords[i].length())); } string exceltablecolumns[]="excelTableDataRecords[i].split(&quot;::&quot;);" for(int j="0;" j<exceltablecolumns.length; j++) apply font styles to cell hssffont objhssffont="objHSSFWorkbook.createFont();" objhssffont.setfontname("arial"); cellstyle objhssfcellstyle="objHSSFWorkbook.createCellStyle();" objhssffont.setboldweight(hssffont.boldweight_normal); objhssffont.setcolor(hssfcolor.black.index); objhssffont.setfontheightinpoints((short)10); objhssfcellstyle.setwraptext(true); objhssfcellstyle.setfont(objhssffont); other column about backlog title hssfcell objnewhssfcellfirstnameadd="objHSSFRow.createCell(j);" objnewhssfcellfirstnameadd.setcellvalue(exceltablecolumns[j]); objnewhssfcellfirstnameadd.setcellstyle(objhssfcellstyle); objhssfworkbook.write(outputstream); catch (ioexception e) e.printstacktrace(); system.out.println("exception raised in downloaduploaded() method download uploaded excel data"); < code></exceltabledatarecords.length;>
<br><br><em><strong>Can anyone help me ?</strong></em>
Shruti Mishra, modificado 8 Anos atrás.

RE: How to download a file from AJAX request in Liferay serveResource(-, -)

New Member Postagens: 22 Data de Entrada: 24/04/15 Postagens Recentes
Hi,

Are you able to achieve this ?

I am having same kind of issue.
thumbnail
Harish Kumar, modificado 8 Anos atrás.

RE: How to download a file from AJAX request in Liferay serveResource(-, -)

Expert Postagens: 483 Data de Entrada: 31/07/10 Postagens Recentes
Hi

You can download the file using ajax but can't be saved to disk because of javascript security limitation. you can simply use the resourceUrl to download the file.
Shruti Mishra, modificado 8 Anos atrás.

RE: How to download a file from AJAX request in Liferay serveResource(-, -)

New Member Postagens: 22 Data de Entrada: 24/04/15 Postagens Recentes
Thanks for explanation Harish.