简体   繁体   中英

How to display images from database in JSF

I have images that are stored in the database as a BLOB. Now I can display them in my jsf pages using Richfaces mediaOutput tag.

Is it possible for images to have path like "/images/image.jpg" while images are stored in the database.

While searching for an answer I came around something like this:

@GET
@Path("/files/{filename}")
@Produces(MediaType.WILDCARD)

Best regards, Ilya Sidorovich

You could write a servlet picking up every request to /image/* or something that suits you. And in your servlet you retrieve the correct data from your database via request parameters. And you write out the data via

response.getOutputStream().write(content); 

(content being the bytearray of you image)

Thank you roel and BalusC!

If anyone comes around this issue, here is what you can do.

    package org.gicm.test;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.inject.Inject;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import org.gicm.cms.CMSDao;
import org.gicm.model.UploadedImage;

@WebServlet("/images/*")
public class TestServlet extends HttpServlet {

    @Inject
    private CMSDao cms;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String imageId = String.valueOf(request.getPathInfo().substring(1)); // Gets string that goes after "/images/".
        UploadedImage image = cms.findImage(imageId); // Get Image from DB.

        response.setHeader("Content-Type", getServletContext().getMimeType(image.getName()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            input = new BufferedInputStream(image.getData()); // Creates buffered input stream.
            output = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[8192];
            for (int length = 0; (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) {}
        }
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM