Upload image to spring mvc

I am using spring 4 and hibernate 4 to upload and receive images to and from the database. I converted the multi-part image to an array of bytes and saved it to the database. My request is how to get this image from the database and display the byte array in jsp without storing it on the local system.

+6
source share
3 answers

Since you did not mention your db structure for storing the image, I would think that you store it in blob type.

Part 1 : ControllerClass

After extracting the image from db, then encode this image with Base64.encode and map this image to your jsp (using java.util.map ).

 Map<String, Object> model = new HashMap<String, Object>(); model.put("myImage", Base64.encode(MyImage)); //MyImage (datatype 'byte[]') is the image retrieved from DB return new ModelAndView("display", model); //display is the name of jsp on which you want to display image 

Part 2 : JSP

Then map it to JSP by decoding the byte array,

 <img id="myImg" name="myImg" src="data:image/jpg;base64,<c:out value='${myImage}'/>" > 
+3
source

Literally what we do

in the dao method

 public InputStream get_user_photo_by_id(int id_user) throws Exception { Blob blob_photo; String sql = "Select b_photo_file from user_master where id_user = ?"; blob_photo = getJdbcTemplate().queryForObject(sql, new Object[] {id_user}, Blob.class); if(blob_photo!=null) return blob_photo.getBinaryStream(); else return null; } 

In the service method, the input stream to the controller simply returns

In the controller

 @ResponseBody @RequestMapping(value = "admin/user/{id}/photo", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public byte[] testphoto(@PathVariable("id") int id_sys_user, HttpSession ses) throws Exception { byte[] thumb = null; InputStream in = UserOps.getUserPhotobyId(id_sys_user); if(in!=null){ thumb = IOUtils.toByteArray(in); } return thumb; } 

now just connect admin / user / {id} / photo or any line that you want to use in <img src = ""> until they match and you get your photo

0
source

You can do it without problems. You must configure a controller that will send an image when the browser requests it. But here the controller does not put it in the model to give it an idea, but it directly generates an HTTP response. Then, in your JSP, you simply provide the appropriate URL.

Here is a (partial) example of what it might be:

 @RequestMapping(value = "/img/{imgid}") public void getFile(HttpServletRequest request, @PathVariable(value = "imgid") long imgid, HttpServletResponse response) throws IOException { contentType = "img/png"; //or what you need response.setContentType(contentType); // find the image bytes into into byte[] imgBytes response.setContentLength((int) imgBytes.length); response.setStatus(HttpServletResponse.SC_OK); OutputStream os = response.getOutputStream(); os.write(imgBytes); } 
0
source

Source: https://habr.com/ru/post/976485/


All Articles