Reputation: 142
I have one requirement where in html page if user click on button then javascript function gets called and in that function ajax call will fetch content of the pdf file from server.
Please find the rest controller as below
@RequestMapping(value = UriMapping.GET_PDF_PATH, method = RequestMethod.POST)
public @ResponseBody WebServiceResponse getPdfPath(HttpServletRequest req,
@RequestParam String fileName, HttpServletResponse response) {
WebServiceResponse res = new WebServiceResponse();
FileInputStream fis = null;
try {
if(!CommonUtil.isBlank(fileName)) {
String filePath = FieldConstant.PDF_PATH + fileName;
File f = new File(filePath);
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline;filename=" + f.getName() );
fis = new FileInputStream(f);
DataOutputStream os = new DataOutputStream(response.getOutputStream());
response.setHeader("Content-Length", String.valueOf(f.length()));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
fis.close();
} else {
res.setSucess(false);
res.setReturnMessage("Something Went Wrong While opening file path !");
}
} catch (Exception e) {
LOGGER.error(e.toString());
res.setSucess(false);
res.setReturnMessage("Something Went Wrong While opening file path !");
}
LOGGER.info("Response" + res.toString());
return res;
}
FieldConstant.PDF_PATH is fixed path at server where all pdf files resides.
Below is the client side jquery function where in I have used window.open() function to open pdf in new tab.
function test(count){
var fileName = pdfGlobal[count].name;
if(fileName != undefined && fileName != "") {
var param = {
"fileName" :fileName
}
$.ajax({
url : '../content/getPdfPath',
type : 'post',
dataType : "json",
data : param,
error : function(error,jqXHR, exception) {
errorMessage(exception);
},
success : function(data) {
if (data) {
window.open(data,'_blank');
} else{
errorMessage(data.returnMessage);
}
}
});
}
}
I am getting parsing error like below
Now as the error suggest I found the % in first place of the response !
Please help me with this.. I know this is not a big issue but I am confused about what goes wrong. Simply not able to find the root cause ...
Thanks in advance.
Upvotes: 0
Views: 1113
Reputation: 46
The ajax is expecting a JSON in return, there is no need for you to use ajax, you can just use window.open, sending fileName by get
window.open('../content/getPdfPath?fileName='+fileName,'_blank');
So you have to change your controller to
@RequestMapping(value = UriMapping.GET_PDF_PATH, method = RequestMethod.GET)
Upvotes: 2