如何使用Javaservlet将图像从MongoDB发送到ExtJS
我有一个Java Servlet,它试图将图像从Mongo DB发送到Ext JS:如何使用Javaservlet将图像从MongoDB发送到ExtJS,java,servlets,extjs,extjs4,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 && act
@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"��ï...
响应是图像的ByTestStream,如下所示:
Ext.Ajax.request({
url: 'ForumImageServlet',
method: 'GET',
params: {
action: 'download'
},});
����JFIF��� "" $(4,$&1'-=-157:::#+?D?8C49:77%w777777777777777777777777777777777777777777777777��Pp"��ï...
如何获得真实图像作为对servlet的响应?
提前谢谢 为什么将
ContentType
设置为text/html
尝试使用
image/jpg
最终的解决方案是将bytestream编码为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();
您可以使用src属性插入img标记,而不是使用ajax请求。当您提供正确的mime类型时,浏览器将加载图像而不是发送图像,您是否可以发送图像url?将更容易处理。不起作用,我认为extjs框架只能读取text/html