[英]How to send an Image from Mongo DB to Ext JS with an Java Servlet
我有一个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的响应? 提前致谢!
为什么将ContentType
设置为text/html
?
尝试使用image/jpg
最终解决方案是将字节流编码为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类型时,浏览器将加载图像
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.