2011-12-24 14 views
26

से एक छवि फ़ाइल आउटपुट आउटपुट में, मेरी हार्ड ड्राइव पर संग्रहीत छवि को कैसे सेवा दें?
उदाहरण के लिए:
मेरे पास पथ 'Images/button.png' में संग्रहीत एक छवि है और मैं यूआरएल file/button.png के साथ एक सर्वलेट में इसकी सेवा करना चाहता हूं।एक सर्वलेट

+0

क्या आप 'सामग्री-प्रकार' के महत्व को जानते हैं जो 'छवि/पीएनजी' पर सेट है या जो भी आपको निम्न उत्तर में उल्लिखित है? – Lion

उत्तर

19
  • /file यूआरएल पैटर्न
  • image/png को Content-Type हैडर सेट लिखने यह response.getOutputStream()
  • को
  • डिस्क से फ़ाइल को पढ़ने के लिए एक सर्वलेट नक्शा (अगर यह केवल PNG का है)
45

यहां कामकाजी कोड है:

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 

     ServletContext cntx= req.getServletContext(); 
     // Get the absolute path of the image 
     String filename = cntx.getRealPath("Images/button.png"); 
     // retrieve mimeType dynamically 
     String mime = cntx.getMimeType(filename); 
     if (mime == null) { 
     resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     return; 
     } 

     resp.setContentType(mime); 
     File file = new File(filename); 
     resp.setContentLength((int)file.length()); 

     FileInputStream in = new FileInputStream(file); 
     OutputStream out = resp.getOutputStream(); 

     // Copy the contents of the file to the output stream 
     byte[] buf = new byte[1024]; 
     int count = 0; 
     while ((count = in.read(buf)) >= 0) { 
     out.write(buf, 0, count); 
     } 
    out.close(); 
    in.close(); 

} 
0

यहां एक और आसान तरीका है।

File file = new File("imageman.png"); 
BufferedImage image = ImageIO.read(file); 
ImageIO.write(image, "PNG", resp.getOutputStream()); 
+1

यह बहुत अक्षम है क्योंकि यह अनावश्यक रूप से छवि को 'BufferedImage' ऑब्जेक्ट में पार्स करता है। यदि आप छवि (आकार, फसल, परिवर्तन, इत्यादि) में हेरफेर नहीं करना चाहते हैं तो इस चरण की आवश्यकता नहीं है। सबसे तेज़ तरीका केवल प्रतिक्रिया इनपुट में छवि इनपुट से unmodified बाइट स्ट्रीम करना है। – BalusC

संबंधित मुद्दे