Reputation: 663
I have a text file called output.txt that will generated inside D:/MPI. I have to download this file but the file which is getting downloaded is completely blank and does not have any contents. I want to download the file output.txt which is in the folder D:/MPI. Here is my code of JSP
<%
String filePath = "D://MPI//output.txt";
String fileName = "outputs";
FileInputStream fileToDownload = new FileInputStream(filePath);
ServletOutputStream output = response.getOutputStream();
response.setContentType("text/plain; charset=utf-8");
response.setHeader("Content-Disposition","attachment; filename="+fileName);
response.setContentLength(fileToDownload.available());
int c;
while((c=fileToDownload.read()) != -1){
out.write(c);
}
output.flush();
output.close();
fileToDownload.close();
%>
Kindly guide me
Upvotes: 0
Views: 162
Reputation: 46871
You are developing a web application and file will be served from the web server. So try to make the path relative to the context of the application instead of using absolute path.
Try with ServletContext#getRealPath() method that returns a String containing the real path for a given virtual path.
Put the output.txt
file inside the war/webapp folder of the project and try below code:
String filePath = request.getServletContext().getRealPath("output.txt");
Note: Always try to avoid the Scriplet instead use JSTL. Move this code in Servlet from the JSP in this case. Treat the JSP for UI and always keep the business and database logic in the Servlet.
Upvotes: 1