Create and show thumbnail (byte[]) in JSF

前端 未结 4 1092
情话喂你
情话喂你 2020-12-16 07:18

I\'m uploading image to server and when image is uploaded it should show me a thumb of uploaded image. Thumbnail is not saved on hard disc I use InputStream and OutputStream

4条回答
  •  别那么骄傲
    2020-12-16 07:47

    The images counts each as a separate request. You cannot process both the HTML response (of JSF) and the image in a single request/response cycle. You need to store the image/thumb somewhere in a datastore which lives longer than a request, e.g. the server's local disk file system (temp folder? webcontent folder?), or a database (temp table?), or in the session.

    First, replace

    by

    so that it get generated as

    (the src should namely point to a valid URL)

    Then, create a HttpServlet which is mapped on an url-pattern of /thumbs/* and implement doGet() roughly like follows:

    Long thumbId = Long.valueOf(request.getPathInfo().substring(1)); // 123
    byte[] thumb = getItFromDiskOrDatabaseOrSessionByThumbId(thumbId);
    String filename = getOriginalFilenameOfUploadedImageOrInventOne();
    
    response.setContentType(getServletContext().getMimeType(filename));
    response.setContentLength(thumb.length);
    response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
    
    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    
    try {
        input = new BufferedInputStream(new ByteArrayInputStream(thumb));
        output = new BufferedOutputStream(response.getOutputStream());
        byte[] buffer = new byte[8192];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }
    

    That's it. More servlet hints can be found in this article.

提交回复
热议问题