Implementing a Simple File Download Servlet

Implementing a simple file download servlet

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.

Java Servlet for file download: Works when started from form submit, not when started from jQuery download

Browsers don't handler XHR responses the same way that they handle "normal" HTTP requests. If your servlet is correctly setting the "Content-disposition" header, then you can just do an ordinary form post.

Servlet for download files from a specific folder?

Since you're handling the data on the doGet method, you can pass a parameter to the servlet where you indicate the name of the file you want to download. For this, you should assume that the file name exists in your base path. The code could go like this:

HTML

<body>
Click on the link to download:
<a href="DownloadServlet?fileName=data.xls">Download Link</a>
</body>

Java Servlet Code:

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//retrieving the parameter by its name
String fileName = request.getParameter("fileName"); //this will return `data.xls`
//using the File(parent, child) constructor for File class
File file = new File(filePath, fileName);
//verify if the file exists
if (file.exists()) {
//move the code to download your file inside here...

} else {
//handle a response to do nothing
}
}

Note that since the code now uses File(String parent, String child) constructor, your filePath should not contain the separator anymore (this will be handled by Java):

public void init() {
// the file data.xls is under web application folder
filePath = getServletContext().getRealPath("");
}

Java Servlet Downloading File

I changed the it so an absolute path is taken e.g.

File f = new File("C:\\data\\" + fileName);

This works. Does having it in a servlet change it so an absolute path is needed and render relative paths unusable? I tested the downloading part outside of a servlet and it works with relative paths or it just downloads into project folder if nothing is specified.

Download file from JSP

I am posting here for anybody here who looking for answer on it.

On JSP file, use this for link

<<li><a href="/reportFetch?filePath=<%=file.getAbsolutePath()%>&fileName=<%=file.getName()%>" target="_top"><%=list[i]%></a><br>

and create the servlet

...

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/reportFetch")
public class Report extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = request.getParameter("filePath");
String fileName = request.getParameter("fileName");

MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mimeType = mimeTypesMap.getContentType(request.getParameter("fileName"));

response.setContentType(mimeType);
response.setHeader("Content-disposition", "attachment; filename=" + fileName);

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(filePath);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();

}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Download a zip from a servlet Java

The fact that the downloaded file is a ZIP isn't relevant (except for the content type), you just want to download a binary file.

PrintWriter isn't good at that, this writer is used to write text output, and the write(int) method you are using :

Writes a single character.

Just use a low level plain OutputStream, its write(int) method :

Writes the specified byte to this output stream.

So just go :

OutputStream out = response.getOutputStream();

You may find some more ways of doing it in this question : Implementing a simple file download servlet



Related Topics



Leave a reply



Submit