2
I would like to recover a file of the type blob
, and to add the extension, without the user having to type this extension when recovering. The way it is, I’m saving and also recovering, but recovering without the extension.
I have the button attach, then the save button.
To recover the file (save in desired folder) I have the recover button.
Attach button:
private void jBAnexarArquivoActionPerformed(java.awt.event.ActionEvent evt) {
caminho = null;
JFileChooser file = new JFileChooser();
file.setFileSelectionMode(JFileChooser.FILES_ONLY);
int i = file.showSaveDialog(null);
if (i == 1) {
JtextFieldLocalArquivo.setText("");
} else {
File arquivo = file.getSelectedFile();
JtextFieldLocalArquivo.setText(arquivo.getPath());
caminho = arquivo.getPath();
}
}
Save button:
String path = caminho;
FileInputStream input = null;
File theFile = new File(path);
input = new FileInputStream(theFile);
byte[] bytes = IOUtils.toByteArray(input);
empresa.setAnexo(bytes);
Retrieve button:
private void jBRecuperarArquivoActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = new SQLConnection().getConnection();
Statement myStmt = null;
ResultSet myRs = null;
InputStream input = null;
FileOutputStream output = null;
try {
myStmt = con.createStatement();
String sql = "select anexo from empresa where idEmpresa = '" + empresaIdField.getText() + "'";
myRs = myStmt.executeQuery(sql);
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String path = selectedFile.getAbsolutePath();
output = new FileOutputStream(selectedFile);
if (myRs.next()) {
input = myRs.getBinaryStream("anexo");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
}
} catch (Exception exc) {
exc.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (output != null) {
try {
output.close();
} catch (IOException ex) {
Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(CondutorInfracaoView.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I did not understand very well: you are saving the file in bank, hence want to recover the extension of this file already persisted, is this?
– Bruno César
Yes, exactly, I have the file in the database, and then the user has the option to make a " download " of this file, however he needs to put the file name and add the extension. And what I wanted was for him to just give up the name, and to automatically add the extension.
– Rodrigo
Includes an answer, see if it helps you :)
– Bruno César