2013-03-25 38 views
0

我有一個Java Servlet的它試圖從蒙戈DB將圖像發送到的Ext JS:如何從蒙戈DB將圖像發送到Ext JS的與Java Servlet的

@Override 
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 

    String action = req.getParameter("action"); 

    if (action != null && action.equals("download")) { 

     resp.setContentType("text/html"); 
     resp.setHeader("Content-Disposition", "attachment;filename=" + "images.jpg"); 

     try { 
      DB db = DataBaseMongoService.getDb("forum_images"); //class that manages Mongo DB access 
      GridFS gfs = new GridFS(db, "image"); 
      GridFSDBFile imageForOutput = gfs.findOne("images.jpg"); 

      InputStream in = imageForOutput.getInputStream(); 

      ServletOutputStream out = resp.getOutputStream(); 
      out.write(IOUtils.toByteArray(in)); 
      out.flush(); 
      in.close(); 
      out.close(); 

     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (NamingException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我的Ext JS調用如下:

Ext.Ajax.request({ 
url: 'ForumImageServlet', 
method: 'GET', 
params: { 
    action: 'download' 
},}); 

的響應是圖像的字節流,看起來像這樣:

����JFIF��� "" $(4,$&1'-=-157:::#+?D?8C49:77%w777777777777777777777777777777777777777777777777��Pp"��ï... 

如何獲得真實圖像作爲對我的servlet的響應? 在此先感謝!

+0

而不是發送圖像,您可以發送圖像網址嗎?將會更容易處理。 – 2013-03-25 14:51:32

回答

0

最終溶液編碼字節流爲Base64:

  byte[] buf = IOUtils.toByteArray(in); 

     String prefix = "{\"url\":\"data:image/jpeg;base64,"; 
     String postfix = "\"}"; 
     String fileJson = prefix + Base64.encodeBytes(buf).replaceAll("\n", "") + postfix; 
     PrintWriter out = resp.getWriter(); 
     out.write(fileJson); 
     out.flush(); 
     in.close(); 
     out.close(); 
1

爲什麼設置ContentTypetext/html

嘗試使用image/jpg

+0

不起作用,我認爲extjs框架只能讀取text/html – user2087455 2013-03-27 11:26:13

0

而不是使用Ajax請求,你可以注入一個img標籤與src屬性。當您提供正確的MIME類型時,您的瀏覽器會加載圖像