0

我有一个 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();
        }
    }
}

我的 Ext JS 调用如下所示:

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

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

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

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

4

3 回答 3

1

你为什么要ContentType设置text/html

尝试使用image/jpg

于 2013-03-27T06:52:54.713 回答
0

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

于 2013-03-27T19:52:12.110 回答
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();
于 2013-03-27T11:25:13.340 回答