I use Glassfish 3.1.2.2, Sql Server 2005, PF 3.4 and Mojarra 2.1.6. Ide Eclipse Juno.
I use stored procedure, and add jar commons-io.1.4 and commons-fileupload.1.2.1
In database, we save all file (pdf, doc, xls, etc.) in varbinary. I have these doubts:
ONE QUESTION
How I can upload any file (pdf, doc, xls, etc.) with p: fileupload and save them to the database?
I undestood the p:fileupload, since documentation. I use this method, handlerFileUpload, for upload a file. Firsts get the inputScream of the event
<p:fileUpload fileUploadListener="#{fileBean.handleFileUpload}" />
public class FileBean {
public void handleFileUpload(FileUploadEvent event) {
UploadedFile file = event.getFile();
//application code
}
}
I used file.getInputStream and sent the stored procedure a BinaryStream setBinaryStream(4, inputStream, (int)inputStream.toString().getBytes().length);
This is good??
TWO QUESTION
How I can download any varbinary file with p:FileDownload?
I recover a varbinary since database with getBytes. Remember I use the stored procedure.
This method is in a class with request scope.
public byte[] ArchivoBin(int CDTPEnlaceImagen, int iddoc) {
Context();
Null_Rs_and_Proc();
Connection(0);
PA(2, 51);
[b]byte[] file = null;[/b]
try {
setProc(getCon().prepareCall(getCall()));
getProc().setInt(1, CDTPEnlaceImagen);
getProc().setInt(2, iddoc);
setRs(getProc().executeQuery());
getRs().next();
[b]file = getRs().getBytes(1);[/b]
System.out.println(file);
}
catch(SQLException e) {
System.out.println("Exception ArchivoBin");
System.out.println(e);
}
CloseConnections();
return file;}
But, when i get the file in bytes, i convert a bytes to inputscream, and then inputscream to DefaultStreamedContent.
This part is a class with request scope.
byte[] bytes = null;
bytes = getRecuperarDatos().ArchivoBin(
1,
idarchivo);
//Archivo is a Session Scope
getArchivo().setFile(new DefaultStreamedContent(
[b]new ByteArrayInputStream(bytes)[/b],
"application/pdf",
nomArchivo));
The f:download not get the file correct, It is corrupt.
<h:commandButton value="Download">
[b]<p:fileDownload value="#{archivo.file}"[/b] />
</h:commandButton>
I don't know why this bad
THREE QUESTION
How I can show pdf with p:media, recovering varbinary files from the database?
This is similar to TWO QUESTION, p:media say "An error has occurred while loading the PDF document"
All is solved, when i save the file in database with the method contents. Specifically, with
public void SubirAlBaseDatos(FileUploadEvent e) {
bytes[] file = e.getFile().getContents();
);
thus, I can show in p:media, and donwload in p:filedownload. Something insignificant was causing the problem.
Thank!! BalusC for your tips source