Issue
I am working on the jsp project. I have an option to download files or images. but the problem is after downloading the file it seems unsupported file format.how to solve that issue?
Solution
First, create a simple link in your jsp page that redirects you to the servlet. instead of jpg, you can put any type of file.
<a href="ServletName?value=filename.jpg">Downlaod</a>
here is the servlet code for download any file from your web directory. Don't forget to create "files" folder in your web-pages directory and paste the file.
try (PrintWriter out = response.getWriter()) {
//fetch the file name from the url
String name = request.getParameter("value");
//get the directory of the file.
String path = getServletContext().getRealPath("/" + "files" + File.separator + name);
//set the content type
response.setContentType("APPLICATION/OCTET-STREAM");
//force to download dialog
response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
FileInputStream ins = new FileInputStream(path);
int i;
while ((i = ins.read()) != -1) {
out.write(i);
}
ins.close();
out.close();
}
that's all. you can check this Download File in jsp and servlet youtube video for more.
Answered By - Almamun
Answer Checked By - Robin (JavaFixing Admin)