A
A
Alexiuscrow2015-03-30 21:41:32
Java
Alexiuscrow, 2015-03-30 21:41:32

How to transfer images to the client?

There is a restful service and there is an android client.
I exchange text information between the server and the client using json. But there was a need for the client to receive images from the server. On the server side, all information (including images) is stored in the database.
How to send images to the client side?
The first thing that comes to mind:

  1. pull images from db to directory
  2. get url for each
  3. generate json with image addresses and additional data
  4. transfer to the client
  5. get images at addresses specified in json

Please share your thoughts. Thank you.
PS Along with the images, you need to transfer additional information (discrimination).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur, 2015-03-30
@Alexiuscrow

You have the right way of thinking - in DTO you put the entire description and a link to the service that produces images. For example myservice.myimageresource?imgId=12345.
The resource can be either a servlet or a rest resource. You take the picture from the database and immediately send it as a byte stream to the client via a GET request. You don't need to write to a temporary folder.
In response to your comment, I edited it here - since there are tags for the code.
Here is a highly simplified example of a servlet that renders an image.

public class PreviewServlet extends HttpServlet {
  
  private static final long serialVersionUID = 1L;
  
  //  это ваше DAO
  private PreviewService previewService = Fascade.getPreviewService();

@Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("image/jpeg");
    //парсим id картинки из запроса
    int imageId = Integer.parseInt(request.getParameter("id"));
    //Тут вы получаете  Entity вашей картинки, одно из полей у которого является массивом байт
    Preview preview = previewService.getByImageId(imageId);
    byte[] bytes  = preview.getBytes();
    response.setContentLength((int) bytes.length);		
    // получаете поток для своих нужд
    ServletOutputStream outStream = response.getOutputStream();
    // отсылаете картинку на клиента
    outStream.write(bytes);
    // закрываете поток
    outStream.close();
  }
}

Almost in a similar way, you can give a resource through rest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question