问题描述:

I have jqgrid and in that I have one custom navigation button to export grid data as a excel.On onClickButton event of this button I am doing a jquery ajax call to retrieve excel data from server.My back-end is Servlet. When I am directly hitting the servlet it gives me a download dialog box but when I call this servlet by ajax call it execute the servlet code and control comes again to ajax success event properly but it not showing the download dialog box.Also after download file I want control on same page where my jqgrid is present it should not navigate to other page.

So please anyone knows why it not showing download dialog box when I am calling through ajax call.Also I have added my servlet code here please check this:

System.out.println("In side TranscationJqgrid");

String userType = request.getParameter("userType");

String searchField = request.getParameter("searchField");

String searchstring = request.getParameter("searchstring");

String searchOper = request.getParameter("searchOper");

System.out.println("searchField = " + searchField

+ "searchstring = " + searchstring + "searchOper = "

+ searchOper + "userType1" + userType);

FileOutputStream fileOutputStream = null;

HSSFWorkbook transactionWorkbook = null;

HSSFSheet transactionDataSheet = null;

try {

/**

* Create a new instance for HSSFWorkBook class and create a

* sample worksheet using HSSFSheet class to write data.

*/

transactionWorkbook = new HSSFWorkbook();

transactionDataSheet = transactionWorkbook

.createSheet("TransactionDataSheet");

/**

* Create two rows using HSSFRow class, where headerRow

* denotes the header and the dataRow1 denotes the cell

* data.

*/

HSSFRow headerRow = transactionDataSheet.createRow(0);

HSSFCellStyle cellStyle = setHeaderStyle(transactionWorkbook);

/* Read the column names from user property file */

String webAppBaseDir = getServletContext().getRealPath("/");

String TxPropFile = webAppBaseDir + "resource"

+ File.separator + "transaction.properties";

LinkedProperties tranProperties = new LinkedProperties();

tranProperties.load(new FileInputStream(TxPropFile));

Enumeration<Object> tranKeyEnum = (Enumeration<Object>) tranProperties.keys();

/**

* Call the setHeaderStyle method and set the styles for the

* all the header cells.

*/

List<HSSFCell> cellList = new ArrayList<HSSFCell>();

int idx = 0;

while (tranKeyEnum.hasMoreElements()) {

String key=(String) tranKeyEnum.nextElement();

HSSFCell HeaderCell = headerRow.createCell(idx);

HeaderCell.setCellStyle(cellStyle);

HeaderCell.setCellValue(new HSSFRichTextString(tranProperties

.getProperty(key)));

cellList.add(HeaderCell);

idx++;

}

List<HSSFRow> rowList = new ArrayList<HSSFRow>();

/* Get Transaction table Metadata */

ColumnData columnData=txManager.getColumnData();

String[] columnType=columnData.getColumnTypes();

/* Get Time zone Offset of Login user. */

String UTCOffset=txManager.getTimeZoneOffset(userDetail[0]);

int row = 1;

ResultSet txResultSet=txManager.getTranSactionRS(userDetail[0], userDetail[1]);

while (txResultSet.next()) {

HSSFRow dataRow = transactionDataSheet.createRow(row);

for (int i = 0; i < tranProperties.size(); i++) {

//Suppose transaction data is retrive by Resultset instead of ResultObject.

if(columnType[i].equalsIgnoreCase("VARCHAR")){

dataRow.createCell(i).setCellValue(txResultSet.getString(i+1));

}else if(columnType[i].equalsIgnoreCase("INT") || columnType[i].equalsIgnoreCase("TINYINT") ){

dataRow.createCell(i).setCellValue(txResultSet.getInt(i+1));

}else if(columnType[i].equalsIgnoreCase("DECIMAL")){

dataRow.createCell(i).setCellValue(txResultSet.getFloat(i+1));

}else if(columnType[i].equalsIgnoreCase("DATETIME")){

dataRow.createCell(i).setCellValue(DateUtil.convertUTCToDisplayInTimezone(

txResultSet.getTimestamp(i+1),UTCOffset));

}

}

rowList.add(dataRow);

row++;

}

fileOutputStream = new FileOutputStream("C:" + File.separator + "sampleexcel.xls");

transactionWorkbook.write(fileOutputStream);

try {

if (fileOutputStream != null) {

fileOutputStream.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

String loc="C:" + File.separator + "sampleexcel.xls";

File f = new File(loc);

int length = 0;

ServletOutputStream op = response.getOutputStream();

ServletContext context = getServletConfig().getServletContext();

String original_filename="tran.xls";

//

// Set the response and go!

//

//

response.setContentType("application/octet-stream");

response.setContentLength( (int)f.length() );

response.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );

//

// Stream to the requester.

//

byte[] bbuf = new byte[1000];

DataInputStream in = new DataInputStream(new FileInputStream(f));

while ((in != null) && ((length = in.read(bbuf)) != -1))

{

op.write(bbuf,0,length);

}

in.close();

op.flush();

op.close();

} catch (Exception ex) {

ex.printStackTrace();

} finally {

/**

* Close the fileOutputStream.

*/

try {

if (fileOutputStream != null) {

fileOutputStream.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

网友答案:

You can't download files by Ajax. This is a security restriction in JavaScript. JS cannot force a Save As dialogue programmatically. You need to download the file by a synchronous request instead.

So, instead of something like

$.get('servleturl', ...);

you need to do

window.location = 'servleturl';
相关阅读:
Top