我试图通过Ajax发布请求下载文件。但是我无法做到这一点,我尝试了很多,但我没有得到。下面是代码,请指导我如何做到这一点。
查询方法
$(document).on({click: function() {
var elementId = $(this).attr('id').split("_");
var air = $('#itineraryAir_${formBean.tripDetailsId}').is(':checked');
var car = $('#itineraryCar_${formBean.tripDetailsId}').is(':checked');
var hotel = $('#itineraryHotel_${formBean.tripDetailsId}').is(':checked');
if(air == true || car == true || hotel == true){
$('#itinerary_modal').modal( 'hide');
$.ajax({
url: "<%=request.getContextPath()%>/viewBooking/downloadItinerary/" +air+"/"+car+"/"+hotel+"/"+elementId[2],
type: 'POST',
dataType: 'text/json',
beforeSend: function() {
},
success: function(data) {
},
complete: function() {
}
}, '.edit_hotel');
}else{
var result="Select itinerary."
showMsg($("#ItineraryMsg"),result,"alert-danger");
}
}
}, '.it_download');
在上面的代码中,我获取了Element-Id,航空,汽车和酒店的详细信息,并通过网址传递了所有这些价值。在Spring控制器类动态我生成PDF文件并生成文件,但我无法显示供用户下载。
服务器端代码
//the below line of code to generate pdf file. It is generating pdf file but I am not able to pass to client.
public @ResponseBody void downloadInPDF(@PathVariable("air") Boolean air,
@PathVariable("car") Boolean car,
@PathVariable("hotel") Boolean hotel,
@PathVariable("tripDetailsId") String tripDetailsId,
HttpServletResponse response,HttpServletRequest request) throws IOException {
TripDetails td = tripDetailsService.get(Integer.parseInt(tripDetailsId));
Users user=userService.getByUserIdNew(String.valueOf(td.getUser().getUserId()));
Employee employee=employeeService.getEmployeeByEmployeeId(user.getEmployee().getEmployeeId());
if(hotel == true){
List<TripHotels> tripHotels = hotelService
.getHotelDetailsByTripId(td);
generatePdf.getPdfFileHotel(AppConstant.ETICKET_PATH, tripHotels, td,employee);
String filePathToBeServed = AppConstant.ETICKET_PATH + td.getTripId()
+ "_Hotel.pdf";
File fileToDownload = new File(filePathToBeServed);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="+td.getTripId() + "_Hotel.pdf");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
}
}