[RESOLVIDO] Upload em banco de dados

12 respostas
E

Boa tarde, Pessoal

estou tentando efetuar upload de arquivos (pdf, jpg ou doc) com (jsf e jpa) em banco de dados mysql em um campo tipo longblob eu encontrei o seguinte codigo abaixo mas nao consegui adaptar ao jpa alguem teria uma solução para isso?

Obs. eu tentei fazer o upload a uma pasta mas quando eu tenho q atualizar o programa (deploy) ele deleta a pasta perdendo seu conteudo.

FileInputStream fis = null;
    PreparedStatement ps = null;
    try {
      conn.setAutoCommit(false);
      File file = new File("myPhoto.png");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setString(1, "001");
      ps.setString(2, "name");
      ps.setBinaryStream(3, fis, (int) file.length());
      ps.executeUpdate();
      conn.commit();
    } finally {
      ps.close();
      fis.close();
    }
  }

12 Respostas

Hebert_Coelho

Como você está fazendo no JPA?

E

estou utilizando dessa forma

public void gravarArquivo() throws FileNotFoundException {
        FileInputStream fis = null;
        File file = new File("myPhoto.png");
        fis = new FileInputStream(file);
        projetoDocumento.setArquivo(setbina);
        FacesContext context = FacesContext.getCurrentInstance();
        boolean resultado = dao.gravarArquivo(projetoDocumento);
        if (resultado) {
            context.addMessage(null, new FacesMessage("Registro salvo com sucesso!"));
        } else {
            context.addMessage(null, new FacesMessage("Erro ao salvar o registro!"));
        }
    }

arquivo gravar dao

public boolean gravarArquivo(ProjetoDocumento projetoDocumento) {
        boolean sucesso = false;
        try {
            emArquivo.merge(projetoDocumento);
            sucesso = true;
        } catch (Exception e) {
            e.getMessage();
        }
        return sucesso;
    }

variaveis

private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected ProjetoDocumentoPK projetoDocumentoPK;
    private String arquivo;
    private String tipo;
Hebert_Coelho

Você está passado o arquivo para dentro de uma string?
private String arquivo;

Olha esse post aqui como fazer:
https://blogs.oracle.com/adf/entry/using_jpa_to_insert_and_retrieve_clob_and_blob_types

E

blz… eu vou dah uma lida nesse post valeu…

E

Bom dia, jakefrog

eu nao consegui achar a classe IOManager e dai o link do exemplo nao funciona vc poderia me dah mais essa forca

IOManager manager=new IOManager();
Hebert_Coelho

Pelo que eu entendi isso aí é uma classe que você teria que criar para tratar as informações.

O post é mesmo para mostrar como mapear para JPA.

E

Nao querendo abusar mas vc teria um exemplo pratico para isso?

grato.

A

boa tarde amigos, faz um tempo que to tentando fazer isso mas fico empacado em alguns conceitos.
eu fiz dessa forma talvez possam me ajudar.

meu beans
@Entity
@Table(name = "anexo")
@NamedQueries({
    @NamedQuery(name = "Anexo.findAll", query = "SELECT a FROM Anexo a")})
public class Anexo implements Serializable {
    private static final long serialVersionUID = 1L;
    
    @Id
    @Column(name = "anexo_id", nullable = false)
    @SequenceGenerator(name="Anexo_Generator", sequenceName="anexo_sequence", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="Anexo_Generator")
    @Basic(optional = false)
    @NotNull
    private Integer anexoId;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "caminho", nullable = false, length = 255)
    private String caminho;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "nome", nullable = false, length = 255)
    private String nome;
    @Basic(optional = false)
    @NotNull
    @Lob
    @Column(name = "arquivo", nullable = false)
    private byte[] arquivo;

    public Anexo() {
    }

    public Anexo(Integer anexoId) {
        this.anexoId = anexoId;
    }

    public Anexo(Integer anexoId, String caminho, String nome, byte[] arquivo) {
        this.anexoId = anexoId;
        this.caminho = caminho;
        this.nome = nome;
        this.arquivo = arquivo;
    }

    public Integer getAnexoId() {
        return anexoId;
    }

    public void setAnexoId(Integer anexoId) {
        this.anexoId = anexoId;
    }

    public String getCaminho() {
        return caminho;
    }

    public void setCaminho(String caminho) {
        this.caminho = caminho;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public byte[] getArquivo() {
        return arquivo;
    }

    public void setArquivo(byte[] arquivo) {
        this.arquivo = arquivo;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (anexoId != null ? anexoId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Anexo)) {
            return false;
        }
        Anexo other = (Anexo) object;
        if ((this.anexoId == null && other.anexoId != null) || (this.anexoId != null && !this.anexoId.equals(other.anexoId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "negocio.entidade.Anexo[ anexoId=" + anexoId + " ]";
    }
    
}
classe ManagedBean
@ManagedBean(name = "anexoMB")
@SessionScoped
public class AnexoMB implements Serializable {
    
    private Anexo anexo;
    
    @EJB
    private AnexoFachada anexoFachada;

    public void AnexoMB(){}

    public Anexo getAnexo() {
        return anexo;
    }

    public void setAnexo(Anexo anexo) {
        this.anexo = anexo;
    }
         
    public String inserir() {
        try {
            anexoFachada.inserir(this.getAnexo());
            return "/anexo/ListarUsuario";
        } catch (Exception e) {
            return "/anexo/InserirUsuario";
        }
    }
}
ae que vem minha dúvida na classe DAO eu posso fazer dessa forma ?
@Stateless
public class AnexoDAO {

    @PersistenceContext
    private EntityManager em;

    public void inserir(Anexo anexo) {
        boolean sucesso = false;
        try {
            em.merge(anexo);
            sucesso = true;
        } catch (Exception e) {
            e.getMessage();
        }
        //return sucesso;
    }
}

onde posso colocar meu metodo que será responsavem por pegar minha imagem e colocar num array de byte ?

E

Boa tarde, alexandrergtk

seguinte para gravar um arquivo pdf eu consegui utilizando a seguinte procedure, mas para imagem ainda nao consegui

public byte[] convertePDF(String arquivo) throws FileNotFoundException{
        File file = new File(arquivo);
        FileInputStream fis = new FileInputStream(file);
        
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        
        try{
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
        } catch (IOException ex) {
            ex.getMessage();
        }
        
        byte[] bytes = bos.toByteArray();
        
        return bytes;
    }

para chamar o metodo

projetoArquivo.setArquivo(convertePDF("C:/documento.pdf"));

se alguem tiver uma solucao para fazer a mesma coisa com imagem agradeco

E

quando eu tento usar a mesma função colocando uma imagem ele dah o seguinte erro

E

Bom dia, consegui resolver o problema da seguinte forma:

pagina

<h:form>
            <rich:fileUpload fileUploadListener="#{projetoControle.enviaArquivo}" id="upload" acceptedTypes="jpg, gif, png, bmp, pdf, doc, xls, docx, xlsx" 
                             uploadLabel="Executar upload" addLabel="Adicionar arquivo" clearAllLabel="Limpar toda lista"
                             clearLabel=" " deleteLabel="Excluir" doneLabel="Arquivo enviado com sucesso!" />

        </h:form>

Controle

public void novoArquivo() {
        projetoArquivo = new ProjetoArquivo();
        projetoArquivo.setProjetoArquivoPK(new ProjetoArquivoPK(1, 1, 2012, dao.verificaOrdem()));
    }

    public void enviaArquivo(FileUploadEvent evento) throws Exception {
        String nomeArquivo = "";
        String extensao = "";
        
        novoArquivo();

        UploadedFile item = evento.getUploadedFile();
        StringTokenizer st = new StringTokenizer(item.getName(), "\\");

        while (st.hasMoreElements()) {
            nomeArquivo = st.nextToken();
        }

        int extDot = nomeArquivo.lastIndexOf('.');
        if (extDot > 0) {
            extensao = nomeArquivo.substring(extDot + 1);
        }

        projetoArquivo.setNome(item.getName());
        projetoArquivo.setTipo(extensao);
        projetoArquivo.setArquivo(item.getData());
        dao.gravarArquivo(projetoArquivo);
    }

dao

public boolean gravarArquivo(ProjetoArquivo projetoDocumento) {
        boolean sucesso = false;

        try {
            emArquivo.merge(projetoDocumento);
            sucesso = true;
        } catch (Exception e) {
            e.getMessage();
        }

        return sucesso;
    }

agradeço ajuda de todos…

valeu.

A

hehehe…agora que vi seu xhtml você está usando richfaces, com essa faces eu já consegui, no momento estou fazendo com primefaces e ele tem mais coisas pra configurar.

vlw

Criado 24 de fevereiro de 2012
Ultima resposta 26 de fev. de 2012
Respostas 12
Participantes 3