How to save an image in the BLOB field of the SQL bd using jsf + primefaces?

Asked

Viewed 134 times

0

I have a table in the database where the BLOB type field already exists to store an image. I wanted to know how to capture an image through JSF/Primefaces and store in this BLOB field of the database.

XHTML:

<h:form enctype="multipart/form-data">
    <p:fileUpload fileUploadListener="#{MeuBean.upload}" label="Escolher" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" fileLimit="1" auto="true" />
</h:form>

NOTE: I use Firebird SQL.

1 answer

0


Opa Ewerton see if it helps you:

inserir a descrição da imagem aqui

In the image above I register a product, simulating an online toy store.

inserir a descrição da imagem aqui

In this other image above, I upload the image to save in the database.

inserir a descrição da imagem aqui

The Final Result, which appears when I do a search by clicking on the category where the product was registered. I saved the image using Blob type in Mysqlserver. In that case I’m using the JSP instead of JSF.

 public class ServletUpload extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;


@SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {

System.out.println("Upload Imagem");

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);


String usuario ="";
String titulo = "";
String descricao = "";
byte[] imagem = null;


try {   
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {

    FileItem item = (FileItem) iter.next(); 

       if(item.getFieldName().equals("user")){
        usuario = item.getString();
        System.out.println(usuario);}

        if (item.getFieldName().equals("titulo")){
        titulo= item.getString();
        System.out.println(titulo);}

        if(item.getFieldName().equals("descricao")){
        descricao = item.getString();
        System.out.println(descricao);}     

        if (item.getFieldName().equals("file"))
        imagem = read(item); //Chamo método para converter a imagem

if (!item.isFormField()) {
if (item.getName().length() > 0) {
System.out.println("chama método");

Imagem img = new Imagem();

img.setTitulo(titulo);
img.setDescricao(descricao);
img.setImagem(imagem);


ImagemDAO dao = new ImagemDAO();
dao.gravar(img);    

HttpSession session = request.getSession(true);
session.setAttribute("user", usuario);

response.sendRedirect("/LojaBrinquedos/Paginas/Admin/Alertas/Imagem/imgSalva.jsp");

}
}
}


} catch (FileUploadException ex) {
ex.printStackTrace();
System.out.println("Upload Failed");
response.sendRedirect("/LojaBrinquedos/Paginas/Admin/Alertas/Imagem/imgError.jsp");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

    private byte[] read(FileItem fi) throws IOException{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream is = fi.getInputStream();
        int read = 0;
        final byte[] b = new byte[1024];

        while ((read = is.read(b)) != -1) {
            out.write(b, 0, read);
        }
        return out.toByteArray();

       }
    }

The image above is mine Servletupload (controller), where I get the data of the fields who are on the image upload page.

The method read I use to convert the image to type Blob before saving to the database, remembering that it is present in the execution of the Servletupload.

In the database to save you will need to do as described below:

ps.setBytes(3, img.getImagem());

It shouldn’t be complicated to do this process for JSF using a Managedbean.

I hope I’ve helped you, any writing there.

Hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.