File Download using JSP and Servlet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

File Download using JSP and Servlet

Share This

Source code for index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- JSP --> <img src="${pageContext.request.contextPath}/image/demo1.jpg" /> <img src="${pageContext.request.contextPath}/image/demo2.jpg" /> </body> </html>
Source code for ImageServlet.java
package com.t4b.demo.controller; import java.io.File; import java.io.IOException; import java.net.URLDecoder; import java.nio.file.Files; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/image/*") public class ImageServlet extends HttpServlet { private String imagePath; public void init() throws ServletException { this.imagePath = "D:/image"; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestedImage = request.getPathInfo(); if (requestedImage == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8")); if (!image.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. return; } String contentType = getServletContext().getMimeType(image.getName()); if (contentType == null || !contentType.startsWith("image")) { response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. return; } response.reset(); response.setContentType(contentType); response.setHeader("Content-Length", String.valueOf(image.length())); Files.copy(image.toPath(), response.getOutputStream()); } }



Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.