Access local directory image from web app running in jetty - java

My web application is written using jsp/javascripts. Backend Java. Have managed to implement the code to save an image outside webapplication, because I dont want to save the images in webapp/images folder(because when the server is down and when rebuild the app, I lose those saved images). What I want is to access those images I saved in my local directory again from my web app but I dont know how to. How can I access my local folder from jetty server, and jetty server is running on the same local machine...

Get the path to /image to store & read files by
getServletContext().getRealPath("/images");
Even you can read the file from external location from your servlet
File image = new File("d:\\image\1.jpg");
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
close(output);
close(input);
}
Also See
Image Servlet

Related

Download servlet is very slow

I have written a servlet which will download the file from a server location. In our own INTRAnet the download seems to be very very slow and also when I have the Adobe addon installed in my browser and if I am downloading a PDF file, the Adobe addon will display the progress bar while downloading the PDF but this is not happening in my case! Below is my code! Should I not response it as attachment?
PrintWriter out = response.getWriter();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setIntHeader("Refresh", 1);
response.setHeader("Content-Disposition",
"inline; filename=\"" + fileNameWithExtension
+ "\"");
FileInputStream fileInStream = new FileInputStream(
filePathWithExtension);
BufferedInputStream bufferInStream = new BufferedInputStream(
fileInStream);
int cnt;
while ((cnt = bufferInStream.read()) != -1) {
out.write(cnt);
}
fileInStream.close();
out.close();
Not sure if there is a better way to do. Basically I tried converting one of my dot net code into this Java Servlet. THe current .NET code is very fast compared to this!
This is hosted on Apache Tomcat and the .NET code is hosted on IIS.
Reading and writing a byte at a time is horrifically inefficient. The canonical way to copy a stream in Java is as follows:
byte[] buffer = new byte[8192]; // or more if you like
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
And you should not use a Writer here, use an OutputStream.

Uploading file to Openshift server with servlet

I'm not sure if this question has been asked before, but I could not find any resources on the internet answering my specific problem.
I am trying to upload a file from an Android app to my Openshift server/gear, where it will be stored. However, the issue I am facing is that whilst the file is being created at the Openshift side (I have checked using FTP), no data is being written to it.
The code snippet from the servlet that writes the data to the file is here:
int BUFFER_LENGTH = 4096;
DataInputStream din = new DataInputStream(req.getInputStream());
String fileName = din.readUTF();
String path = System.getenv("OPENSHIFT_DATA_DIR") + "/uploads/" + fileName + ".txt";
File f = new File(path);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[BUFFER_LENGTH];
int length = 0;
while ((length = din.read(buffer, 0, BUFFER_LENGTH)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
din.close();
It all seems to be correct, to me at least, and it worked when I tested it on a local tomcat server. For some reason, however, it doesn't work with Openshift, so there must be something I am missing.
Luckily there is a help center article for just this issue:
https://forums.openshift.com/how-to-upload-and-serve-files-using-java-servlets-on-openshift
It details the code for both uploading, and serving files on OpenShift via a Java Servlet, using the openshift data directory

Access (.mdb) file corrupted during servlet write to the client

This was originally a part 2 of a different thread, but another use suggested that I separate the part 2 into it's own topic, so here we go. Original thread is here (Original Thread)
I am using Jackcess to create a V2010 mdb file that I need to transfer to a client that will use Access 2013 to open it. Jackcess itself works - V2010 creates a file that Access 2013 can open when the file is FTP'd to the client by a third party software, such as FAR. However, when I try to upload this file to the client through the servlet (as is the goal of this project), Access on the client says "Unrecognized database format "...file name...". This is the code used for upload. Code itself works, file is transferred, has a non-zero size if it's saved - but Access cannot open it.
Note, for content type I also tried vnd.msassess and octed-stream, with same unsuccessful results. Also, I tried closing the db and creating the FileInputStream from the file name, and, as in the example, tried to create FileInputStream by calling mydb.getFile(). No difference.
response.setContentType("application/vnd.ms-access");
String fileName = "SomeFileName.mdb";
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
Database mydb = generateMDBFile();
FileInputStream fis = new FileInputStream(mydb.getFile());
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
Why does this code corrupt the mdb file? This happens every time, regardless of the size (I tried a tiny 2 column/1 row file, and a huge file with 40 columns and 80000 rows)
Thank you!
You forgot to fill the buffer.
Use
// ...
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
// ...

Servlet - Force overwrite downloaded file

How to change this code to force overwrite existing previously opened file saved on drive? It's part of servlet for opening pdf files on client side.
response.reset();
response.setContentType("application/pdf");
response.setContentLength(file.length());
response.setHeader("Content-disposition", "inline; 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];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
}
finally
{
close(output);
close(input);
}
Each next copy of opened file has a new index, e.g. test.pdf, test(1).pdf and so on
You can't control that.
That is dependent on client's OS file system implementation
The best you can do it to configure the client browser to ask whether to overwrite or not, for example in Firefox it is:
To my knowledge asking to overwrite is the default behavior in Opera.
before going to write check whether the given file is exist or not?
using file api file.exists() if it exists, delete given file using file api file.delete() and continue with writing process

Stream linearized PDF from servlet to browser (fast web view)

I'm running a web app that provides a servlet. this servlet opens a pdf file from a Network File System and finally streams it to the requesting browser.
All the pdf files are linearized by adobe lifecycle pdf generator and ready for fast web view.
unfortunately, the fast web view does not work. I guess it's a problem of how to open and stream the file in java code and the setting of response header info.
if i deploy a test pdf within my webapp onto the jboss AS and open it directly from the browser by url, the incrementel loading works.
can anyone help me?
Here's the code of my servlet:
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-Disposition",
"inline;filename=" + documentReference);
response.setHeader("Accept-Ranges", "bytes");
File nfsPDF = new File(NFS_DIRECTORY_PATH + documentReference);
FileInputStream fis = new FileInputStream(nfsPDF);
BufferedInputStream bis = new BufferedInputStream(fis);
ServletOutputStream sos = response.getOutputStream();
byte[] buffer = new byte[(int) nfsPDF.length()];
while (true) {
int bytesRead = bis.read(buffer, 0, buffer.length);
if (bytesRead < 0) {
break;
}
sos.write(buffer, 0, bytesRead);
}
sos.flush();
//... closing...
Let's see. You want to send a file in parts, right? Then you should check Range header (HTTP Header) and send only bytes in this range. I'm correct?
I'm not familiar with "PDF fast web view" feature, but in you're code your're first reading the file completely into buffer and then you write it out. The client won't receive anything before the call to sos.flush(). In fact your while loop is obsolete because there will always be just one run.
Maybe you should try to read/write the stuff blockwise.
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = bis.read(buffer, 0, buffer.length);
if (bytesRead < 0) {
break;
}
sos.write(buffer, 0, bytesRead);
sos.flush();
}
sos.flush();

Categories

Resources