ExtJS Handling Response Holding PDF as StreamingOutput - java

I am working with extJS 4.2.1 and I would like to display a PDF file that is stored in a ResponseBuilder as a StreamingOutput object. When the response is returned to the extjs controller, Im not sure how to handle it in order to display the PDF on a new page.
#GET
#Path("/images/{imageNumber}/{imageType}")
#Produces({"application/pdf"})
public Response openDocument(#PathParam("company") String company,
#PathParam("imageNumber") String imageNumber, #PathParam("imageType") String imageType){
final File imageFile = new File("/someRemoteDir/28717484.pdf");
StreamingOutput stream = new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
InputStream input = new FileInputStream(imageFile);
byte[] buf = new byte[8192];
int c = 0;
while ((c = input.read(buf, 0, buf.length)) > 0) {
output.write(buf, 0, c);
output.flush();
}
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
ResponseBuilder response = Response.ok(stream);
response.type("application/pdf");
response.status(200);
response.header("Accept-Ranges","bytes");
response.header("Cache-Control",null);
response.header("Pragma",null);
response.header("Content-Disposition","inline; filename=\"" + imageDoc.getNumber() +"\"");
return response.build();
}
extJS controller
Ext.Ajax.request({
method: 'GET',
url: CTrack.Config.appPath('loads/images/' + imageNumber + '/' + imageType),
jsonSubmit: true,
success: function(response, opt) {
if (response.status == 200) {
NOT SURE WHAT TO DO HERE?.........
} else {
me.displayError(errorMsg);
} },
failure: function(response, opt) {
console.log('Failure');
}
...

Related

when i write a code for download pdf but only one pdf is download(bcz this pdf is text only) another pdf is not open on spring boot and angular 12

enter image description here
enter image description here
Controller on spring boot--->
#PostMapping(value = "/getpdfs")
public void getSchemeNotes(HttpServletRequest request, #RequestBody String requestBody,HttpServletResponse response) {
MessageLogger.debug(logger, String.format("getSchemeIpoNote(requestBody = %s)", requestBody));
Map<String, String> query = Utility.getQueryParameters(request);
try {
Scheme scheme = (Scheme) DataParsingUtility.convertJsonStringtoObject(requestBody, Scheme.class);
String fileNames= scheme.getSchemeNote();
//String fileNames = "Campus Activewear Limited - IPO Note Apr'2022-compressed.pdf";
String outputPath = ParameterConfiguration.getUploadDirectory() + File.separator + fileNames;
MessageLogger.debug(logger, String.format("fileNames(fileNames = %s)", fileNames));
MessageLogger.debug(logger, String.format("outputPath(outputPath = %s)", outputPath));
InputStream is = null;
try {
is = new FileInputStream(new File(outputPath));
response.setHeader("Content-Disposition", "attachment;filename=\""+fileNames+"\"");
response.setHeader(Constants.FILE_NAME, fileNames);
response.setHeader( "application","blob");
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
finally {
if (is != null) {
is.close();
}
}
} catch (Exception ex) {
MessageLogger.debug(logger, "Error while getting Scheme Note file!", ex);
}
}
angular controller-->
viewNote(obj: any) {
var reqData = {
"schemeNote" : obj
}
this.schemeService.getSchemeNote(null, reqData, (rsp) => {
this.messageLoggerService.debug("request>>>"+JSON.stringify(reqData));
this.messageLoggerService.debug("response>>>>"+rsp);
this.commonService.processDownloadResponse(rsp);
});
}

How can i download the PDF file in spring mvc?

this is my file path
public final static String BOOKINGPDFFILE= "D:/Hotels/pdf/";
This below code is what I have written to download pdf from the above resource folder
Pdf="column name in database i used for storing in database"
#RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(#PathVariable("pdf") String fileName, HttpServletResponse response,HttpServletRequest request) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
Files.copy(file.toPath(),response.getOutputStream());
} catch (IOException ex) {
System.out.println("Contract Not Found");
System.out.println(ex.getMessage());
}
}
Here is the way, hope it help.
#RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(#PathVariable("pdf") String fileName, HttpServletResponse response) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
if (file.exists()) {
// here I use Commons IO API to copy this file to the response output stream, I don't know which API you use.
FileUtils.copyFile(file, response.getOutputStream());
// here we define the content of this file to tell the browser how to handle it
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
response.flushBuffer();
} else {
System.out.println("Contract Not Found");
}
} catch (IOException exception) {
System.out.println("Contract Not Found");
System.out.println(exception.getMessage());
}
}
You may try something like this:
#RequestMapping(method = { RequestMethod.GET }, value = { "/downloadPdf" })
public ResponseEntity<InputStreamResource> downloadPdf()
{
try
{
File file = new File(BOOKINGPDFFILE);
HttpHeaders respHeaders = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("application/pdf");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
respHeaders.setContentDispositionFormData("attachment", file.getName());
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
And in your web page you can write the link in this way:
download PDF
You need to create an implementation of AbstractPdfView to achieve this.. You can refer this link https://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-pdf-file-via-abstractpdfview/
Here is the Detailed answer for your question.
let me start with the server side code:
Below class is used to create pdf with some random content and return the equivalent byte array outputstream.
public class pdfgen extends AbstractPdfView{
private static ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
public ByteArrayOutputStream showHelp() throws Exception {
Document document = new Document();
// System.IO.MemoryStream ms = new System.IO.MemoryStream();
PdfWriter.getInstance(document,byteArrayOutputStream);
document.open();
document.add(new Paragraph("table"));
document.add(new Paragraph(new Date().toString()));
PdfPTable table=new PdfPTable(2);
PdfPCell cell = new PdfPCell (new Paragraph ("table"));
cell.setColspan (2);
cell.setHorizontalAlignment (Element.ALIGN_CENTER);
cell.setPadding (10.0f);
//cell.setBackgroundColor (new BaseColor (140, 221, 8));
table.addCell(cell);
ArrayList<String[]> row=new ArrayList<String[]>();
String[] data=new String[2];
data[0]="1";
data[1]="2";
String[] data1=new String[2];
data1[0]="3";
data1[1]="4";
row.add(data);
row.add(data1);
for(int i=0;i<row.size();i++) {
String[] cols=row.get(i);
for(int j=0;j<cols.length;j++){
table.addCell(cols[j]);
}
}
document.add(table);
document.close();
return byteArrayOutputStream;
}
}
Then comes the controller code : here the bytearrayoutputstream is converted to bytearray and sent to the client side using the response-entity with appropriate headers.
#RequestMapping(path="/home")
public ResponseEntity<byte[]> render(HttpServletRequest request , HttpServletResponse response) throws IOException
{
pdfgen pg=new pdfgen();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
byte[] contents = null;
try {
contents = pg.showHelp().toByteArray();
}
catch (Exception e) {
e.printStackTrace();
}
//These 3 lines are used to write the byte array to pdf file
/*FileOutputStream fos = new FileOutputStream("/Users/naveen-pt2724/desktop/nama.pdf");
fos.write(contents);
fos.close();*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
//Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> respons = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return respons;
}
The header should be set to "application/pdf"
Then comes the client side code :
Where you can make ajax request to server to open the pdf file in new tab of the browser
$.ajax({
url:'/PDFgen/home',
method:'POST',
cache:false,
xhrFields: {
responseType: 'blob'
},
success: function(data) {
//alert(data);
let blob = new Blob([data], {type: 'application/pdf'}); //mime type is important here
let link = document.createElement('a'); //create hidden a tag element
let objectURL = window.URL.createObjectURL(blob); //obtain the url for the pdf file
link.href = objectURL; // setting the href property for a tag
link.target = '_blank'; //opens the pdf file in new tab
link.download = "fileName.pdf"; //makes the pdf file download
(document.body || document.documentElement).appendChild(link); //to work in firefox
link.click(); //imitating the click event for opening in new tab
},
error:function(xhr,stats,error){
alert(error);
}
});
Try this
#Controller
#RequestMapping("/download")
public class FileDownloadController
{
#RequestMapping("/pdf/{fileName}")
public void downloadPDFResource( HttpServletRequest request,
HttpServletResponse response,
#PathVariable("fileName") String fileName)
{
//If user is not authorized - he should be thrown out from here itself
//Authorized user will download the file
String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/pdf/");
Path file = Paths.get(dataDirectory, fileName);
if (Files.exists(file))
{
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename="+fileName);
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

png file Uploading Restful Web Service java

I try to write an image file uploading post method for my web service. Here is my post method. The image file can be uploaded into post method but can not converted into Image type.
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/html")
public Response uploadFile(#FormDataParam("file") File file2) throws IOException {
InputStream IS = null;
String output = "";
try {
IS = new FileInputStream(file2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
try {
if (file2 != null && IS != null) {
Image img = ImageIO.read(IS);
if (img != null) {
output = "image file transmission sucessed";
} else {
String out = convertStreamToString(IS);
output = "file uploaded into post method, however can not transfer it into image type "+
"\n"+ out;
}
} else if (file2 == null) {
output = "the file uploaded into post method is null";
}
} catch (IOException e) {
e.printStackTrace();
}
return Response.status(200).entity(output).build();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
The "file uploaded into post method, however can not transfer it into image type "+"\n"+ out; message is shown. The reason I believe is the inputStream contants extral file information + the content of the image. When I try to convert the inputStream back to Image, I need to find a way to get rid of the extra info passed.
here is my new reversion:
#POST
#Path("/images")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response imageUpload(
#FormDataParam("image") InputStream hereIsImage,
#FormDataParam("image") FormDataContentDisposition hereIsName) {
String path = "f://";
if (hereIsName.getSize() == 0) {
return Response.status(500).entity("image parameter is missing")
.build();
}
String name = hereIsName.getFileName();
path += name;
try {
OutputStream out = new FileOutputStream(new File(path));
int read;
byte[] bytes = new byte[1024];
while ((read = hereIsImage.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
return Response.status(500)
.entity(name + " was not uploaded\n" + e.getMessage())
.build();
}
return Response.status(200).entity(name + " was uploaded").build();
}
However, when I upload the image, an error pops up:
[ERROR] An exception occurred during processing of the au.edu.rmit.srtwebservice.util.rest.testWS class. This class is ignored.
com/sun/jersey/core/header/FormDataContentDisposition
the testWS.calss is where my method is.
public Response uploadFile(#FormDataParam("file") File file2)
File input may not work because you most likely be sending an octet stream from your client. So try using InputStream as the input type and hopefully it should work.
public Response uploadFile(#FormDataParam("file") InputStream file2)

The request sent by the client was syntactically incorrect- when uploading a file

I get the follwing exception when i try to upload a file in spring :
The request sent by the client was syntactically incorrect.
this is how i submit the value through ajax :
function uploadComment(viewName,answers){
var file_data = $("#CIMtrek_daily_originator_comments").val();
alert("file_data "+file_data);
$.ajax({
type : "POST",
url : "CIMtrek_Compliance_Daily_Shipments_FileUpload",
data: {
uploadFile : file_data,
id : '0'
},
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
alert("File Uploaded");
}
});
}
and this is my controller method :
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(#RequestParam("uploadFile") MultipartFile uploadItem ) {
System.out.println(" CIMtrek_Compliance_Daily_Shipments_FileUpload : ");
String uploadedFileName="";
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
System.out.println("size::" + uploadItem.getSize());
fileName = "/WEB-INF/resources/Attachment/"+ uploadItem.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("fileName:" + uploadItem.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName =uploadItem.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
Please help me to resolve this.
You need to use serialize() instead of val() as below
data: $("#your_form").serialize();
$.ajax({
type : "POST",
contentType:false,
url : "CIMtrek_Compliance_Daily_Shipments_FileUpload",
data: $("#your_form").serialize(),
success: function (msg) {
global.getElementById("CIMtrek_uploadedFileName").innerHTML=msg;
alert("File Uploaded");
}
});

call back in spring file upload

i have followed this to upload file to server. the file is getting uploaded but after uploading the file it gives the page name as the filename.extension.jsp and gives HTTP Status 404 here is the screen shot :
But i want to show the user only the status message saying File is uploaded. how to do this?
Here is my spring controller method:
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName = "";
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
fileName = request.getRealPath("") + "/resources/Attachment/"+uploadItem.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName = uploadItem.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
Please help me to find,
Best Regards
Hi #Anto you can do it somethig like this,
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request, ModelMap map) {
String uploadedFileName = "";
...
uploadedFileName = uploadItem.getOriginalFilename();
// ---------------------------------------------------------------------------
if("" != uploadedFileName || null != uploadedFileName) {
map.put("message", new String("File is uploaded."));
} else {
map.put("message", new String("File is not uploaded."));
}
// ---------------------------------------------------------------------------
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
And JSP you put
<c:out value="${message}"></c:out>
I hope help you :)

Categories

Resources