Implementing a simple file download servlet [duplicate] - java

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 2 years ago.
How should I implement simple file download servlet?
The idea is that with the GET request index.jsp?filename=file.txt, the user can download for example. file.txt from the file servlet and the file servlet would upload that file to user.
I am able to get the file, but how can I implement file download?

Assuming you have access to servlet as below
http://localhost:8080/myapp/download?id=7
I need to create a servlet and register it to web.xml
web.xml
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
DownloadServlet.java
public class DownloadServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String fileName = "";
String fileType = "";
// Find this file id in database to get file name, and file type
// You must tell the browser the file type you are going to send
// for example application/pdf, text/plain, text/html, image/jpg
response.setContentType(fileType);
// Make sure to show the download dialog
response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");
// Assume file name is retrieved from database
// For example D:\\file\\test.pdf
File my_file = new File(fileName);
// This should send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
}

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().
If it's not, you'll need to manually copy it to response output stream:
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
You'll need to handle the appropriate exceptions, of course.

Try with Resource
File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
String.format("attachment; filename=\"%s\"", file.getName()));
OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();

The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.
You can easily achieve it through:
HttpServletResponse.sendRedirect()

And to send a largFile
byte[] pdfData = getPDFData();
String fileType = "";
res.setContentType("application/pdf");
httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
out.write(pdfData);
System.out.println("sendDone");
out.flush();

Related

Upload the file into the webapp folder

The user to upload the file with the txt extension to my system. I want this file to be accessible as www.exp.com/text_file.txt
But I could not do it.
Project/src/main/webapp/text_file.txt , If I drop the file under the webapp I can get it.
But how can I create txt file in webapp?
new File(---); --> this code does not what I want. It creates under the eclipse folder.
Project
->pom.xml
->src
->main
->java
->resources
->webapp
->WEB-INF
Assuming you are using servlets , this code should work (let's place file into webapp/resources)
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
// Getting ServletContext from request
ServletContext ctx= req.getServletContext();
// Get the absolute path of the file
String filename = ctx.getRealPath("resources/file.text");
// getting mimeType of the file
String mime = ctx.getMimeType(filename);
// Error handling
if (mime == null) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Setting MIME content type
res.setContentType(mime);
// Getting file object
File file = new File(filename);
// Setting content length header
res.setContentLength((int)file.length());
// FileInputStream to read from file
FileInputStream in = new FileInputStream(file);
// Obtain OutputStream from response object
OutputStream out = res.getOutputStream();
// Writing to the OutputStream
byte[] buffer = new byte[1024];
int bytes = 0;
// we stop when in.read returns -1 and read untill it does not
while ((bytes = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
// Clean up, closing resources
out.close();
in.close();
}

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();

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();

Output an image file from a servlet [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 6 years ago.
How to serve an image, stored on my hard drive, in a servlet?
For Example:
I have an image stored in path 'Images/button.png' and I want to serve this in a servlet with the URL file/button.png.
Here is the working code:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext cntx= req.getServletContext();
// Get the absolute path of the image
String filename = cntx.getRealPath("Images/button.png");
// retrieve mimeType dynamically
String mime = cntx.getMimeType(filename);
if (mime == null) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mime);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
out.close();
in.close();
}
map a servlet to the /file url-pattern
read the file from disk
write it to response.getOutputStream()
set the Content-Type header to image/png (if it is only pngs)
Here's another very simple way.
File file = new File("imageman.png");
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, "PNG", resp.getOutputStream());

Categories