Inserting Image into the Database with Java Web

1

I'm having trouble inserting an image into a database. I already have a save method and I'm including a photo field, but I'm not sure how to implement to upload the image.

Who can help me, I'll be grateful.

Below are the codes:

package com.br.mvsistemasjavaweb.controler.usuarios;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;

import com.br.mvsistemasjavaweb.controler.departamento.Departamentos;
import com.br.mvsistemasjavaweb.model.usuarios.TipoUsuarios;
import com.br.mvsistemasjavaweb.model.usuarios.Usuario;
import com.br.mvsistemasjavaweb.model.usuarios.UsuarioAtivo;
import com.br.mvsistemasjavaweb.repository.usuarios.Usuarios;
import com.br.mvsistemasjavaweb.service.usuarios.CadastroUsuariosService;
import com.br.mvsistemasjavaweb.util.FacesMessages;

@Named
@ViewScoped
public class UsuariosBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private Usuarios usuarios;

    @Inject
    private CadastroUsuariosService cadastroUsuarios;

    @Inject
    private FacesMessages mensagens;

    private List<Usuario> todosUsuarios;

    private Usuario usuarioEdicao = new Usuario();

    private Usuario usuarioSelecionado;

    private Departamentos departamento;

    private Part foto;

    public void salvarUsuarios() throws IOException {
        // Linha para inserção da imagem
        this.usuarioEdicao.setFoto(IOUtils.toByteArray(this.foto.getInputStream()));
        this.cadastroUsuarios.salvar(usuarioEdicao);
        this.usuarioEdicao = new Usuario();
        this.consultar();
        mensagens.info("Usuario Salvo com Sucesso!");
    }

// ... Restante do código

Component of the view that inserts the photo:

                <p:outputLabel value="Foto de Perfil" />
                <p:fileUpload value="#{usuariosBean.foto}" mode="simple" skinSimple="true"/> 
    
asked by anonymous 15.03.2015 / 03:30

1 answer

0

Your usersBean class must be annotated with @SessionScoped, it is a restriction of the prime fileUpload. An "alternative" to not keeping this class in session is to create another ManagedBean just to upload. In the framework that we work we have an example of this: link

    
16.03.2015 / 13:34