Loading
Reading Image with a Servlet

Java Quick Notes

Refresh Your Java - Before Java Interview

We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

Go to SiteMap

Q)  How you read an Image with a Servlet ?


Ans)

Two important Steps  while reading an Image with a Servlet.

i) Getting the MIME type and setting to Response .

 String mimeType = getServletContext().getMimeType(filename);    
      res.setContentType(mimeType); 


ii) Reading the Image in small chunks as follows
        byte[] buf = new byte[1024];  
 

public class ImageReader extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)  
                                throws ServletException, IOException {  
        
      FileInputStream fis = null;  
      String filename  = "C:/Img/yourOwn.jpg";    
      String mimeType = getServletContext().getMimeType(filename);    
      if (mimeType == null) {    
          sc.log("Could not get MIME type of "+filename);    
          res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);    
          return;    
       }    
    
      res.setContentType(mimeType);  
            
      ServletOutputStream output = res.getOutputStream();  
      try {  
        fis = new FileInputStream(new File(filename));  
        byte[] buf = new byte[1024];  
        int i = 0;  
        while ((i = fis.read(buf)) != -1) {  
            output.write(buf, 0, i);  
        }  
        output.flush();  
      } finally {  
          fis.close();  
          output.close();  
      }  
     }  
 } 
}



Back to top

------------------------- We hope you got necessary Info On -----------------------------------------

Reading Image with a Servlet


Reading Image with a Servlet

-------------------------------------------------------------------------------------------------------



Face Book
Request for a Mock Interview/Training

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free