Output an image file from a 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 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());

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

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

How to offer download of local PDF file in Java?

I have JBoss running as application server and somewhere on my HD there is a PDF file, that gets created when the user clicks on a specific action. Let's say the file is here: C:/PDF/doonot/10.07.2012/doonot.pdf. How can I offer this file as download? I already did it for a CSV file, but I don't know how to do it with PDF.
Any help is much appreciated.
as i wrote on Is there a common way to download all types of files in jsp?
you can use something like this:
public HttpServletResponse getFile (HttpServletRequest request ,HttpServletResponse httpServletResponse, .......){
HttpServletResponse response = httpServletResponse;
InputStream in =/*HERE YOU READ YOUR FILE AS BinaryStream*/
String filename = "";
String agent = request.getHeader("USER-AGENT");
if (agent != null && agent.indexOf("MSIE") != -1)
{
filename = URLEncoder.encode(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8");
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename=" + filename);
}
else if ( agent != null && agent.indexOf("Mozilla") != -1)
{
response.setCharacterEncoding("UTF-8");
filename = MimeUtility.encodeText(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8", "B");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
}
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
out.write(by, 0, index);
index = in.read(by, 0, 32768);
}
out.flush();
return response;
}
UPDATE:
Dont forget that you can use the InputStream as this:
// read local file into InputStream
InputStream inputStream = new FileInputStream("c:\\SOMEFILE.xml");
or you can use it even like this
//read from database
Blob blob = rs.getBlob(1);
InputStream in = blob.getBinaryStream();
You can simply write a servlet wich read the pdf and write it to the response output stream.
Exemple here : http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html
Yes Gustav is right. Java doesn't discriminate amongst file types. A file is a file, if you did it for csv, it should also work for pdf.

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

Implementing a simple file download 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 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();

Categories