Write byte array to pdf file on click of view - java

I am done with writing the file content to pdf file on click of view, But it's not opening automatically.Can any one help. Thanks in advance.And please correct me if anything wrong here.
#RequestMapping(value = { "/view" }, method = RequestMethod.GET)
public static byte[] loadFile(#RequestParam("file_path") String file_path,#RequestParam("file_name") String fileName,HttpServletResponse response, HttpServletRequest request,HttpServletResponse resp) throws IOException, DocumentException {
FileInputStream inputStream = null;
try {
String filePath = file_path.replace("/", "\\");
File file = new File(filePath);
inputStream = new FileInputStream(file);
filePath.endsWith(".pdf");
return readFully(inputStream, filePath, fileName, resp, request,
resp);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
here i am calling the below method and written the code for opening a file automatically.
#ResponseBody
public static byte[] readFully(FileInputStream inputStream,
#RequestParam("file_path") String file_path,
#RequestParam("file_name") String fileName,
HttpServletResponse response, HttpServletRequest request,
HttpServletResponse resp) throws IOException, DocumentException {
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
Document doc = new Document();
PdfWriter.getInstance(doc, baos);
doc.open();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName + ".pdf");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "No-cache");
response.setContentLength(baos.size());
ServletOutputStream outn = response.getOutputStream();
outn.flush();
baos.writeTo(outn);
File f = new File("C:\\Users\\Downloads\\" + fileName + ".pdf");
if (f.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(f);
} else {
System.out.println("Awt Desktop is not supported!");
}
} else {
System.out.println("File is not exists!");
}
System.out.println("Done");
return baos.toByteArray();
}

You can write your inputstream into spring fileInputStream.
You can do this just writing input stream in httpservletResponse.
Please change your all code with below method. You can achieve your goal.
#RequestMapping(value = { "/view" }, method = RequestMethod.GET)
#ResponseBody
public void loadFile(#RequestParam("file_path") String file_path,#RequestParam("file_name") String fileName,HttpServletResponse response, HttpServletRequest request,HttpServletResponse resp) throws IOException, DocumentException {
String filePath = file_path.replace("/", "\\");
File file = new File(filePath);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
try {
FileInputStream fileInputStream = new FileInputStream(file);
FileCopyUtils.copy(fileInputStream, httpServletResponse.getOutputStream());
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Related

JSF command button can be clicked only once when calling servlet for file download

I have some command buttons in a jsf, one of which when clicked when create a file and download. In the action class that handle the jsf action , I create the url object that has the URL for calling the Servlet.
This all works , the file is downloaded one time when I click on the button , but the issue is , I cannot click on the button or any other command buttons on the page after this. Why is the request not complete? Please help.
<h:commandButton id="filedownloadbtn" action="#{fileDownloadInit.submit}" value = "thisform">
Action
try {
String baseURL = facesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
String url = baseURL + "/DataloadServlet";
facesContext.getCurrentInstance().getExternalContext().redirect(url);
return null;
} finally {
facesContext.responseComplete();
}'
DataloadServlet
public Object[] getFileNameAndData(HttpServletRequest request)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//does some processing...
return new Object[] {fileName, stream.toByteArray()};
}
FileDownloadservlet
public abstract class FileDownloadservlet extends javax.servlet.http.HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Object[] file = getFileNameAndData(request);
if (file != null)
{
String fileName = (String)file[0];
byte[] fileData = (byte[])file[1];
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName +"\"");
response.setHeader("Cache-Control", "no-cache, no-store"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
String contentType = "application/vnd.ms-excel";
response.setContentType(");
response.setContentLength(fileData.length);
try
{
OutputStream output = response.getOutputStream();
output.write(fileData);
output.flush();
output.close();
}
catch (IOException ex)
{
}
}
}

Unable to download file in Spring MVC

My Controller to which the request is mapped-
I return the value from AJAX, to the controller-
$.ajax({
type: 'GET',
dataType: 'json',
contentType:"application/json",
url:"/Putty/downloadProcess/?param="+param
});
#RequestMapping(value = "/downloadProcess", method = RequestMethod.GET)
protected void download(#RequestParam("param") String value, HttpServletResponse response)
throws ServletException, IOException {
Properties prop = new Properties();
InputStream input = new FileInputStream("config.properties");;
prop.load(input);
System.out.println(value);
String path = prop.getProperty("path.MS1");
String filepath= path.concat(value);
System.out.println(filepath);
File downloadFile = new File(filepath);
FileInputStream inStream = new FileInputStream(downloadFile);
String mimeType = "application/octet-stream";
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile);
response.setHeader(headerKey, headerValue);
System.out.println(response);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
This displays the filenames on my JSP
<c:forEach var="listValue" items="${files}">
<label onClick="download('${listValue}')">${listValue}</label>
<br>
</c:forEach>
The problem is that, I can see the MIME type on my console, along with the value returned by AJAX- The filename. But I do not get the Download dialog box, when I click on the file names, displayed on my JSP. Am I not handling the requests properly or I am missing something else.
Thanks!
Try it
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream");
if (file.isFile())
{
response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFile.getName() + "\"");
try (FileInputStream inputStream = new FileInputStream(downloadFile ))
{
IOUtils.copy(inputStream, out);
}
}
The Open/Save dialogue appears by default so we can not force anything. It is a browser specific settings that you cant change on the client side.
For Mozilla Firefox example :

How can I reuse JAX-RS Response into HttpServletResponse?

I have a Servlet which makes a request to my Rest API, and I want it to return the API Response content to the final user through the HttpServletResponse.
The content is actually a .xls file to download which I put in the Response with the StreamingOutput Object.
How can I do that ? I can't cast the Response into a HttpServletResponse
Rest API method :
#GET
#Produces( MediaType.APPLICATION_JSON )
#Path("bla")
public Response getTopicByName() {
final Workbook wb = new HSSFWorkbook();
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream output) throws IOException, WebApplicationException {
wb.write(output);
}
};
responseBuilder = responseBuilder.entity(stream);
responseBuilder = responseBuilder.status(Response.Status.OK);
responseBuilder = responseBuilder.header("Content-Disposition", "attachment; filename=" + device + ".xls");
return responseBuilder.build();
}
Servlet POST method :
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response res = target. request().get();
if (res.getStatus() == 200) {
// how to put res stream into response stream ?
ServletOutputStream stream = response.getOutputStream();
}
client.close();
}
EDIT :
I tried TedTrippin method and after finding out the way to recover an InputStream from the Response, it worked well.
But I keep getting corrupted xls files. And it is quite annoying. I don't get those corrupted files when I make the request directly from the browser.
Got any clues where it comes from ?
POST method :
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url + param + format);
Response res = target.request().get();
if (res.getStatus() == 200) {
response.setHeader("Content-Disposition", "attachment; filename=test.xls");
InputStream in = res.readEntity(InputStream.class);
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
while (in.read(buffer) >= 0) {
out.write(buffer);
}
out.flush();
}
client.close();
}
Simplest way is to read the response stream and write it straight to the response output stream. Either use a library function from IOUtils or Guava or pure java...
try (InputStream in = ...;
OutputStream out = ...) {
byte[] buffer = new byte[1024];
while (in.read(buffer) >= 0)
out.write(buffer);
} catch (IOException ex) {
...
}
A nicer (depending on your view) way would be to read/save the response as a temporary file then you could return that or write it to the output stream.
Third approach would be to create a pipe, but I don't think that would be applicable here.

Download pdf directly to browser when generated with itext

I am using itext to generate a pdf file from an html string. I get this error in my console:
Uncaught Error: Syntax error, unrecognized expression: %PDF-1.4
This is the code in my controller.
#RequestMapping(value = "/print",method = RequestMethod.POST)
public void print(String html,HttpServletResponse response,HttpServletRequest request) throws IOException,DocumentException {
try{
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// step 3
document.open();
document.add(new Paragraph(html));
// step 5
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
// the contentlength
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
}
catch(DocumentException e) {
throw new IOException(e.getMessage());
}
what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do this like this:
#RequestMapping(value="/displayProcessFile/{processInstanceId}", method=RequestMethod.GET)
public ResponseEntity<byte[]> displayProcessFile(#PathVariable String processInstanceId) throws UnauthorizedUserAccessException{
Document processFile=null;
try {
processFile = documentService.retrieveProcessFile(Long.parseLong(processInstanceId));
} catch (ProcessFileNotFoundExpection e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.add("content-disposition", "attachment;filename=" + processFile.getDocName());
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(processFile.getContent(), headers, HttpStatus.OK);
return response;
}

Return File From Resteasy Server

Hi, I wanted to return a file from a resteasy server. For this purpose, I have a link at the client side which is calling a rest service with ajax. I want to return the file in the rest service. I tried these two blocks of code, but both didn't work as I wanted them to.
#POST
#Path("/exportContacts")
public Response exportContacts(#Context HttpServletRequest request, #QueryParam("alt") String alt) throws IOException {
String sb = "Sedat BaSAR";
byte[] outputByte = sb.getBytes();
return Response
.ok(outputByte, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = temp.csv")
.build();
}
.
#POST
#Path("/exportContacts")
public Response exportContacts(#Context HttpServletRequest request, #Context HttpServletResponse response, #QueryParam("alt") String alt) throws IOException {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=temp.csv");
ServletOutputStream out = response.getOutputStream();
try {
StringBuilder sb = new StringBuilder("Sedat BaSAR");
InputStream in =
new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
byte[] outputByte = sb.getBytes();
//copy binary contect to output stream
while (in.read(outputByte, 0, 4096) != -1) {
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
}
return null;
}
When I checked from the firebug console, both of these blocks of code wrote "Sedat BaSAR" in response to the ajax call. However, I want to return "Sedat BaSAR" as a file. How can I do that?
Thanks in advance.
There're two ways to to it.
1st - return a StreamingOutput instace.
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
InputStream is = getYourInputStream();
StreamingOutput stream = new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
output.write(IOUtils.toByteArray(is));
}
catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").build();
}
You can return the filesize adding Content-Length header, as the following example:
return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").header("Content-Length", getFileSize()).build();
But if you don't want to return a StreamingOutput instance, there's other option.
2nd - Define the inputstream as an entity response.
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download() {
InputStream is = getYourInputStream();
return Response.code(200).entity(is).build();
}

Categories

Resources