need a servlet to download a file from path like /home/Bureau - java

Need a servlet to download a file from path like /home/Bureau.. in jee gwt
I used this but isn't work
and I went to download all file's type image
String filePath = request.getParameter("file");
String fileName = "test";
FileInputStream fileToDownload = new FileInputStream(filePath);
// ServletOutputStream output = response.getOutputStream();
response.setHeader("Content-Type", "image/png");
//response.setContentType("image/png");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".png\"");
// response.setContentLength(fileToDownload.available());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) {
//output.write(readBytes);
response.getOutputStream().write(readBytes);
}
response.getOutputStream().close();
fileToDownload.close();
fileToDownload.close();

The problem is at below line where you are writing no of bytes not actual bytes. Here readBytes represents no of bytes read at a time where as buffer contains actual bytes that is read.
response.getOutputStream().write(readBytes);
Try
OutputStream outputStream = response.getOutputStream();
while ((readBytes = fileToDownload.read(buffer)) != -1) {
outputStream.write(buffer,0,readBytes);
}
outputStream.close();
I suggest you to call response.getOutputStream() single time.
Your code will give you IndexOutOfBoundsException if the size of the file is less than 10000 bytes because of below line
fileToDownload.read(buffer, 0, 10000)
Change it to
fileToDownload.read(buffer)
Use ServletContext to get file path.
ServletContext context = getServletContext();
For more info have a look at below posts:
Writing image to servlet response with best performance.
How do I return an image from a servlet using ImageIO?

Related

How to set client side Folder path(Like D://new folder) for download file in spring contoller?

I have one spring controller, I want to download file in specific path like D:// or K://, But right now it will be download in downloads folder by default.
I am taking my file from /WEB-INF/ folder (server side located in Tomcat folder) and i want to write in client machine D:\ drive please see my below code is something wrong please let me know. I am using google crome.
Thanks in Advance
public void downloadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//ServletContext context = request.getServletContext();
String filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/") + "/"+"out.json";
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
//String fullPath = appPath + filePath;
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
System.out.println("downloadFile.getName()" + downloadFile.getName());
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
You cannot decide where the client will save the downloaded file on server side - in fact, you cannot even affect whether it will save it anywhere at all! That's for the client (e.g. Chrome) to decide.
See Chrome help for how to change default download location in Chrome.

Tomcat 8 file download speed issue

I am using Tomcat 8 and I have functionality to download large files from tomcat server places in context docbase folder.
Below is the piece of code I am using the file to download:
PrintWriter out = response.getWriter();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition",
"attachment; filename=filename);
FileInputStream fileInputStream = new FileInputStream("filepath");
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
When I download a file it is downloading with a speed of 65KB/sec
from the save server. If I place the same file in Apache server and try to download the download speed is 135KB/sec.
Could someone help me speed up the file download from Tomcat?
The problem is that reading and writing a byte at a time to unbuffered streams is very inefficient. Looking at this previous answer and adapting it to your code, we could use:
// Assume ServletResponse response
ServletOutputStream servletOutputStream = response.getOutputStream();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition",
"attachment; filename=filename);
FileInputStream fileInputStream = new FileInputStream("filepath");
// Choose a bigger value if you want
byte[] buffer = new byte[4096];
int n;
while ((n = fileInputStream.read(buffer) != -1)
{
servletOutputStream.write(buffer, 0, n);
}
fileInputStream.close();
servletOutputStream.close();
The above should be very efficient and hopefully equal or surpass your reported Apache speeds.

Servlet read/output binary file nor same checksum as original file

I have a servlet (JSP) that reads a file from disk and sends it as http response.
The downloaded file has not the same sha1sum that the original and some files seems to be corrupted.
My code is this:
File file = new File((String)application.getAttribute("path")+"/"+item);
if (!file.exists()){
RequestDispatcher dispatcher = application.getRequestDispatcher("/not_found.jsp?item="+item);
dispatcher.forward(request, response);
return;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=\""+item+"\"");
Locale.setDefault(new Locale("ES","ve"));
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream outs = response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
System.out.println(new java.util.Date()+"\tStart download\t"+item+"\t"+request.getRemoteAddr()+"\t"+request.getRemoteHost());
while(fileIn.read(outputByte, 0, 4096) != -1)
{
outs.write(outputByte, 0, 4096);
}
fileIn.close();
outs.flush();
outs.close();
System.out.println(new java.util.Date()+"\tEnd Download\t"+item+"\t"+request.getRemoteAddr()+"\t"+request.getRemoteHost());
Why does downloaded file have different sha1sum as original file and why some but not all downloaded files are corrupt?
You must put the number of read bytes in a variable, and just write as many bytes that you read.
Your implementation always writes the whole buffer of 4096 bytes, no matter of how many bytes that actually were read.
Something like this:
int i = 0;
while( (i=fileIn.read(outbyteByte, 0, 4096)) != -1){
outs.write(outputByte,0,i);
}

What should be the content type to download any file format in jsp?

I want to make a provision to download all file types...Is there any way to download any file format in jsp...
My code snippet:
String filename = (String) request.getAttribute("fileName");
response.setContentType("APPLICATION/OCTET-STREAM");
String disHeader = "Attachment";
response.setHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object
File fileToDownload = new File(filename);
response.setContentLength((int) fileToDownload.length());
FileInputStream fileInputStream = new FileInputStream(fileToDownload);
int i = 0;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
If I specify setContentType as APPLICATION/OCTET-STREAM, pdf, text, doc files are getting downloaded.... But the problem is with image files...
What is problem with image files? I want to download all image file types...
I searched similar questions but could not find proper answer...
Thanks...
Finally I somehow managed to do this...
The problem is with JSP's "Out.write", which is not capable of writing byte stream...
I replaced jsp file with servlet...
The code snippet is:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String filename = (String) request.getAttribute("fileName");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename="+filename);
File file = new File(filename);
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[(int)file.length()];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, (int)file.length()) != -1)
{
out.write(outputByte, 0, (int)file.length());
}
}
Now I can download all types of files....
Thanks for the responces :)
Check the following link ,
JSP download - application/octet-stream
Might help you to resolve the issue.
for images you should use setContentType(image/jpg).you can checkout this link for mime types
http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm

java restful web service image gallery

i have a project where i'm dealing with restful web service, especially need to return images for android client, when client is entering the "gallery" he need to get a root collection which have to return all of folders and file(images) from static folder on running server. Can someone help with this? How can i return images that could be accessed by client for detailed view?
You only need to getHttpServletRequest and HttpServletResponse type of object and apply below code -
String filePath = request.getParameter(YOUR_FILE_PATH_PARAMETER");
String filePath = filePath;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="
+ "YOUR_FILE_NAME");
// Get it from file system
FileInputStream in = new FileInputStream(new File(filePath));
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
// copy binary content to output stream
while (in.read(outputByte, 0, 4096) != -1) {
out.write(outputByte, 0, 4096);
in.close();
out.flush();
out.close();

Categories