Upload and Donwload JSF + Primefaces + Mysql files

How to recover file name saved as database BLOB and display on screen? I am using a repeat loop, to retrieve, the Valo saved in the database column, but returns memory values ([B@2248bd40):insert the description of the image here

Another inconsistency, which is occurring is: when the user uploads to the database, the file is successfully saved( any file), but to run the donwload I must inform the code, and only allows the output the file in the extension formatted in the source code (example: pdf, doc, etc.). The problem is, it will only come out according to the defined extension. Do you have any way to perform the donwload of the file in original format, which was saved?

Follows the method:

public void download() {
    ResultSet rs;
    try {

        Connection con = Conexao.getConnection();

        PreparedStatement st = con.prepareStatement("SELECT image FROM uploadfile WHERE codigo = (?) ");
        st.setInt(1, codigo);

        rs = st.executeQuery();
        while (rs.next()) {
            InputStream stream = rs.getBinaryStream("image");
            file = new DefaultStreamedContent(stream, "image/jpg", "Arquivo.pdf");
        }
        con.close();

        FacesMessage message = new FacesMessage("Exito", " File descarregado com sucesso.");
        FacesContext.getCurrentInstance().addMessage(null, message);

    } catch (Exception erro) {
        erro.printStackTrace();
        FacesMessage message = new FacesMessage("Erro ao executar download.");
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
} 
Author: Denis Rudnei de Souza, 2017-05-16

1 answers

It is not possible to retrieve the name of a blob file by Java, it would be necessary to convert this BLOB to some other type of object for this, which would not be very cool to do.

In this case what I tell you to do is:

  • Save the file name to another column in the database; or
  • change the storage form of the file to recover it in some simpler way without using the BLOB.

Is this, following your current approach not I imagine that it is easy to realize this functionality, maybe changing the approach everything becomes easier. Good luck!

 1
Author: Bonifacio, 2017-05-18 15:02:14