Uploading and Donwloading JSF files + Primefaces + Mysql

2

How to retrieve the file name saved as BLOB from the database and display on the screen? I am using a loop to retrieve, the value saved in the database column, but it returns memory values ([B @ 2248bd40):

Another inconsistency, which is occurring is: When the user uploads to the database, the file is successfully saved (any file), however to execute the donwload I must inform the code, and only allows the output of 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. Is there any way to download the file in original format, which was saved?

The method follows:

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);
    }
} 
    
asked by anonymous 16.05.2017 / 02:38

1 answer

1

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

In this case what I tell you to do is:

  • Save the file name in another database column; or
  • Change the way the file is stored to recover it in some simpler way without using the BLOB.

That's it, following your current approach, I do not imagine that this functionality is easy to accomplish, perhaps changing the approach makes everything easier. Good luck!

    
18.05.2017 / 17:02