Convert Byte Array To File And Download - java

I am getting byte array from web service. this byte array is the pdf file. Below code execute well and download file on browser. But this file is seems corrupt. Also additional copy of file gets created on server which I am trying to avoid.
byte[] rawFile = myService.getDocument(param1, param2);
try (BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(rawFile));
FileOutputStream fileOutputStream = new FileOutputStream("myfile-1.pdf")) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment;filename=myfile-1.pdf");
response.flushBuffer();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
In a nutshell, below are 2 issue.
Downloaded file (on browser) is seems corrupt and not open. Generic pdf error message appears.
File which created on server is opening fine and shows content. But this file should not be physically present on server.

Downloaded file (on browser) is seems corrupt and not open.
Because you never sent the file content to the browser.
this file should not be physically present on server.
Then why did you explicitly write it there using FileOutputStream?
You need to write the file content to the response.
byte[] rawFile = myService.getDocument(param1, param2);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=myfile-1.pdf");
OutputStream out = response.getOutputStream();
out.write(rawFile);
// no need to close or flush, that happens automatically when you return

Related

How do I send an image to the output in JSP

I want to open my servlet which basically checks my permissions and if allowed, shows me a picture like it would be a real jpeg. My code so far:
File file = new File("C:/test.jpeg");
FileInputStream fis = new FileInputStream(file);
byte imageBytes[] = new byte[(int) file.length()];
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
response.getOutputStream().flush();
But somehow the image it tries to show me in the browser is corrupted. I already checked that the file exists, as the image.length is not zero. What did I do wrong?
You should start using the newer NIO.2 File API that was added in Java 7, mostly the Files class, because it makes the job much easier.
Option 1: Load file into byte[]
byte[] imageBytes = Files.readAllBytes(Paths.get("C:/test.jpeg"));
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
try (OutputStream out = response.getOutputStream()) {
out.write(imageBytes);
}
Option 2: Stream the file without using a lot of memory (recommended)
Path imageFile = Paths.get("C:/test.jpeg");
response.setContentType("image/jpeg");
response.setContentLength((int) Files.size(imageFile));
try (OutputStream out = response.getOutputStream()) {
Files.copy(imageFile, out);
}

How can'i save the result of a PrintWriter in file instead of display it in the console

I have this example which displays the result in a console
HttpServletResponse presponse
presponse.setContentType(text/xml; charset=UTF-8)
PrintWriter lout = presponse.getWriter();
lout.println(var);
lout.close();
But i want to save the result in downloadable file instead of display it in the console
can you help me please
If you do not want to provide the file content as the HTTP response payload, you should not write it into response.getWriter(). By the way, you're not "displaying it in the console", you're sending it as the HTTP response to the client's request.
To save a file with that content on the local disk, just create a FileOutputStream and write the file content in there.
As for the HTTP response, just provide the URL to the newly created downloadable file (as a Location header or whatever).
You can do something like, you need to set correct mime-type and content-length header.
File downloadFile = new File(filePath);
FileInputStream inStream = new FileInputStream(downloadFile);
// 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();

Java : download file outside server context

I need to save a file and download file in directory outside server context.
I am using Apache Tomacat
I am able to do this in directory present in webapps directory of application
If my directory structure is as follows,
--src
--WebContent
-- uploaddir
-- myfile.txt
Then I am able to download in by simply.
download
But, problem is when file is in some other directory say d:\\uploadedfile\\myfile.txt
then I wont be able to download it, as resource is not in server context as above.
I have file path to uuid mapping,
like,
d:\\uploadedfiles\\myfile.txt <-> some_uuid
then I want file should be downloaded, on click of following,
download
So, How to make file downloadable when it is outside the server context,
I heard about getResourceAsStream() method which would do this , But would any one help me on how to do this, probably with simple code snippet?
Try the below code which you can write in filedownloadservet. Fetch the file name from the request parameter and then read and write the file.
If you need to do some security checks then do that before processing the request.
File file = new File("/home/files", "file name which user wants to download");
response.setContentType(getServletContext().getMimeType(file.getName()));
response.setContentLength(file.length());
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buf = new byte[2048];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
//log it
}
}
// do the same for input stream also
}
here i found the answer,
response.setContentType("application/msword");
response.setHeader("Content-Disposition","attachment;filename=downloadname.doc");
File file=new File("d:\\test.doc");
InputStream is=new FileInputStream(file);
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
Base path will not work that is for HTML and it works if the base path is also exposed by your web server which does not look like case here.
To download an arbitary file you need to open the file using a FileInputStream (and surround it by a buffered input stream), read a byte, then send that byte from your servlet to the client.
Then there are security concerns, so should google that (basically not give access to any file but only file that is to be shared, audit download etc as needed.
Again in your servlet set the mime type etc and then open a input stream and write the bytes to the output stream to client

Why pdf files downloads as corrupted?

I wrote small program for downloading files via url. Every other files format I can open properly, but for downloaded pdf it's impossible.
public static void saveFile(String fileUrl, String destinationFile) throws IOException {
URL url = new URL(fileUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
os.flush();
is.close();
os.close();
}
Do I need special way for handling pdf downloads?
When I try to get selected pdf via URL in browser it's displays properly
EDIT
Added flush() to code, still no success
Trying to open damaged pdf in browser (FF) returns error:
File does not begin with '%PDF-'
Adobe Reader returns:
File could not be open because it is either not a supported file type
or because file has been damaged.
Damages pdf has smaller size (about 80%) than original
The damaged pdf files has website html code inside.

How can I open Excel file through servlet

I have used jxls.jar library to export data in to excel format and stored in file with *.xls format.
How can I open or promote dialog box for open or save this file after complete writing process into file using servlet
the all proccess for writing in to file is done in separate function..
I understand that you have the Excel file as a File object and that you want to provide this as a download to the client. You need to set the Content-Disposition header to attachment to let the client show a Save As dialogue. You also need to set the Content-Type header as well to let the client know what file type it is so that it can eventually associate the right application with it for the case that the enduser would like to open it immediately. Finally, setting the Content-Length header is preferably as it improves serving performance (otherwise the Servlet API will fall back to chunked encoding which requires a bit more bytes and processing time).
After setting the proper headers, it's just a matter of writing the InputStream from the File to the OutputStream of the HttpServletResponse the usual Java IO way.
private static final int DEFAULT_BUFFER_SIZE = 8192; // 8KB.
// ...
File file = createExcelFileSomehow();
// ...
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length; (length = input.read(buffer)) > -1;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
Are you asking how to send the file to the user?
This may help: Servlet for serving static content
Then just create an HTML link to the servlet from whatever you use for presentation.
Add a header Content-Disposition: attachment
This code snippet should help you. When you give Content disposition as inline in the IE browsers it will open the excel as such without prompting the dialog box.
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition","inline;fileName=" + fileName);
final java.io.OutputStream os = response.getOutputStream();
call the createExcel function passing OutputStream Object
os.flush();
os.close();

Categories