I have an Java Servlet which tries to send an Image from Mongo DB to 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 call looks like this:
Ext.Ajax.request({
url: 'ForumImageServlet',
method: 'GET',
params: {
action: 'download'
},});
The Response is the bytestream of the image that looks like this:
����JFIF��� "" $(4,$&1'-=-157:::#+?D?8C49:77%w777777777777777777777777777777777777777777777777��Pp"��ï...
?
How can I get a real image as a response to my servlet? Thanks in advance!
Why do you set ContentType
to text/html
?
Try using image/jpg
The final solution was encoding the bytestream to 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();
instead of using ajax requests, you can inject an img-tag with src attribute. when you provide the correct mime-type, your browser loads the image
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.