如何使用Java Servlet将图像从Mongo DB发送到Ext JS

时间:2013-03-25 14:47:41

标签: java servlets extjs extjs4

我有一个Java Servlet试图将图像从Mongo DB发送到Ext JS:

@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();
        }
    }
}

My Ext JS调用如下所示:

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

Response是图像的字节流,如下所示:

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

如何获得真实的图像作为对我的servlet的响应? 提前谢谢!

3 个答案:

答案 0 :(得分:1)

为什么将ContentType设为text/html

尝试使用image/jpg

答案 1 :(得分: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();

答案 2 :(得分:0)

而不是使用ajax请求,您可以使用src属性注入img-tag。当您提供正确的mime类型时,您的浏览器会加载图像