I have a table with users and a i have to select one to get the list of files so i can download. Everything works fine but if i already download the file and i try to click again to download i get the java.io.IOException: Stream Closed , but if i download the file and select again the user to get the list of files i can download the file.
The problem is i can't download more than once without have to select the user and get the list of files.
This is how i get the files when i select the user to get the list of files.
public void obtenerRequisitos() {
try {
archivos = new ArrayList<>();
lstArchivos = new ArrayList<>();
if (SelectedInscripcion != null) {
lstArchivos = d.getArchivosInscripciones(String.valueOf(SelectedInscripcion.getId()));
for (Archivos a : lstArchivos) {
InputStream input = new FileInputStream(a.getRuta());
String extension = a.getRuta().substring(a.getRuta().lastIndexOf('.'));
file = new DefaultStreamedContent(input, a.getRequisitosPromo().getRequisitos().getTipoArchivo(), a.getRequisitosPromo().getRequisitos().getFormato() + extension);
archivos.add(new ClsArchivos(a.getRequisitosPromo().getRequisitos().getDescripcion(), file));
}
}
} catch (Exception ex) {
Logger.getLogger(AsignarEntrevistaBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
this is a class that i use to store the list of files
public class ClsArchivos implements Serializable{
private String descripcion;
private StreamedContent file;
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public StreamedContent getFile() {
return file;
}
public void setFile(StreamedContent file) {
this.file = file;
}
public ClsArchivos() {
}
public ClsArchivos(String descripcion, StreamedContent file) {
this.descripcion = descripcion;
this.file = file;
}
}
and this is part of the xhtml where the filedownload is
<p:dataTable style="margin-bottom: 25px;" id="requisitos" value="#{asignarEntrevistaBean.archivos}" var="a">
<f:facet name="header">
Listas de Requisitos por Solicitud
</f:facet>
<p:column headerText="Descripcion">
<h:outputText value="#{a.descripcion}" />
</p:column>
<p:column headerText="Archivos">
<p:commandButton value="Download" ajax="false" icon="ui-icon-arrowthick-1-s">
<p:fileDownload value="#{a.file}" />
</p:commandButton>
</p:column>
</p:dataTable>
Related
i am uploading multiple images through p:fileUpload and showing uploaded images in datagrid but after upload the blank panel is created inside datagrid
<p:panelGrid columns="1" layout="grid" style="width: 1000px">
<p:outputLabel value="Upload Images"></p:outputLabel>
<p:fileUpload mode="advanced" multiple="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" dragDropSupport="true"
update="messages,updimgsfields,carouselcomp" sizeLimit="100000"
fileUploadListener="#{drawingattachmnt.handleFileUpload}"></p:fileUpload>
<!-- <p:graphicImage id="gimPhoto" value="#{fileuploadSection.image}" /> -->
</p:panelGrid>
<p:fieldset id="updimgsfields" legend="Uploaded Images">
<p:dataGrid id="updimgsdatagrid" var="upldimg"
value="#{drawingattachmnt.uploadedimages}" columns="4">
<p:panel id="drawingattachmntpnl" header="#{upldimg.displayId}"
style="text-align:center">
<h:panelGrid columns="1" cellpadding="5"
style="width: 100%; height: 200px;">
<p:graphicImage value="#{upldimg.imgcontent}" cache="false"
stream="true">
<f:param id="imgId" name="photo_id" value="#{upldimg.id}" />
</p:graphicImage>
</h:panelGrid>
</p:panel>
<p:draggable for="drawingattachmntpnl" revert="true"
handle=".ui-panel-titlebar" stack=".ui-panel" />
</p:dataGrid>
</p:fieldset>
// file upload function inside bean
public void handleFileUpload(final FileUploadEvent event) throws IOException {
if (event.getFile().getContents() != null) {
final ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream();
BufferedImage uploadedImage = null;
byte[] imageBytes = null;
try {
final String imageType = event.getFile().getContentType() != null
|| event.getFile().getContentType().split("/") != null ? event.getFile().getContentType()
.split("/")[1] : "jpeg";
uploadedImage = ImageIO.read(event.getFile().getInputstream());
ImageIO.write(uploadedImage, imageType, byteArrOutputStream);
imageBytes = byteArrOutputStream.toByteArray();
updimg.setImgcontent(new DefaultStreamedContent(new ByteArrayInputStream(imageBytes), imageType));
updimg.setId(UUID.randomUUID().toString().substring(0, 8));
updimg.setDisplayId("FIG: ");
uploadedimages.add(updimg);
} catch (final IOException io) {
} finally {
try {
byteArrOutputStream.close();
// imageInputStream.close();
} catch (final IOException e1) {
e1.printStackTrace();
}
uploadedImage.flush();
}
final FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Successful", "File uploaded Successfully "));
}
// List POJO
import org.primefaces.model.StreamedContent;
public class UploadImage {
public String displayId;
public String id;
public StreamedContent imgcontent;
public UploadImage() {
}
public UploadImage(final String id, final String displayId, final StreamedContent imgcontent) {
this.id = id;
this.displayId = displayId;
this.imgcontent = imgcontent;
}
#Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UploadImage other = (UploadImage) obj;
if (this.id == null ? other.id != null : !this.id.equals(other.id)) {
return false;
}
return true;
}
public String getDisplayId() {
return displayId;
}
public String getId() {
return id;
}
public StreamedContent getImgcontent() {
return imgcontent;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public void setDisplayId(final String displayId) {
this.displayId = displayId;
}
public void setId(final String id) {
this.id = id;
}
public void setImgcontent(final StreamedContent imgcontent) {
this.imgcontent = imgcontent;
}
}
I need to show images in datagrid dynamically, but i am getting blank image panel inside datagrid. what should be done ?
I have a web application that uses PrimeFaces components. I am trying to download a file from the database to be saved to someones client computer. In the code, I am writing the byte array to the file object shown below. However, I do not know how to trigger the download dialog bar when the function is triggered. Can someone please help?
Download function in Download bean
public void fileDownload(int id) throws IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
DBConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demeter2.0", "root", "root");
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(Animal.class.getName()).log(Level.SEVERE, null, ex);
}
PreparedStatement pst = null;
try {
if (DBConn != null) {
String sql = "Select * FROM graph WHERE id='" + id + "'";
pst = (PreparedStatement) DBConn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if (!rs.next()) {
} else {
rs.beforeFirst();
while (rs.next()) {
// File file = new File("c:/newfile.png");
Blob b = rs.getBlob(2);
byte barr[] = new byte[(int) b.length()];
barr = b.getBytes(1, (int) b.length());
InputStream is = new ByteArrayInputStream(barr);
System.out.print("hello");
file = new DefaultStreamedContent(is, "image/png", "chart.png");
System.out.print(file);
}//end while
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
pst.close();
DBConn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
download.xhtml
<h:form>
<p:dataTable var="download" value="#{download.allGraph()}">
<p:column headerText="Id">
<h:outputText value="#{download.id}" />
</p:column>
<p:column headerText="Date Added">
<h:outputText value="#{download.date}" />
</p:column>
<p:column headerText="Download">
<p:commandLink id="downloadLink" value="Download" ajax="false">
<p:fileDownload value="#{download.fileDownload(download.id)}" />
</p:commandLink>
</p:column>
</p:dataTable>
</h:form>
If you look carefully at showcase
you will see that you need to call function that returns StreamedContent. You could changed your function from void to StreamedContent and at the end add return file;
I want to download file in my jsf page, and below is my jsf page
<h:form id="MyListForm">
<p:commandButton value="Attachments" icon="ui-icon-transferthick-e-w" actionListener="#{myTeam.downloadImageDialogue}"
style="font-size: 10px;font-weight: bolder;vertical-align: text-bottom;width: 80px;" >
</p:commandButton>
</h:form>
and my bean code is:
public void downloadImageDialogue() {
RequestContext.getCurrentInstance().openDialog("AttachmentDialog");
}
and my dilogue xhtml page is:
<h:body>
<h:form>
<p:dataTable var="Attachment" value="#{attachmentDialogView.attachmentList}" rows="10">
<p:column headerText="File Name">
<h:outputText value="#{Attachment.fileName}" />
</p:column>
<p:column headerText="Download Attachment">
<p:commandLink ajax="false" id="dwldLink" action="#{attachmentDialogView.downloadImage}">
<f:setPropertyActionListener value="#{Attachment.id.itemId}" target="#{attachmentDialogView.imageItemId}" />
<f:setPropertyActionListener value="#{Attachment.fileName}" target="#{attachmentDialogView.fileName}" />
<f:setPropertyActionListener value="#{Attachment.id.callId}" target="#{attachmentDialogView.callID}" />
<p:graphicImage value="images/dnld1.png" width="25" height="25"/>
<p:fileDownload value="#{attachmentDialogView.file}"/>
</p:commandLink>
</p:column>
</p:dataTable>
</h:form>
</h:body>
and bean code is:
#ManagedBean(name = "attachmentDialogView")
#ViewScoped
public class AttachmentDialogView implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Attachment> attachmentList;
private String imageItemId;
private String fileName;
private DefaultStreamedContent file;
String callID;
#ManagedProperty("#{myTeamService}")
private MyTeamService service;
#PostConstruct
public void init() {
attachmentList = service.getAttachmentList(service.getCallId());
}
public void downloadImage() {
Session session = HibernateUtil.getSessionFactory().openSession();
Attachment attachment = null;
byte[] bImage;
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
try {
if (getCallID() == null || getCallID().equals("")) {
RequestContext.getCurrentInstance().execute("PF('check_dialog').show()");
} else {
attachment = (Attachment) session.createCriteria(Attachment.class).add(Restrictions.eq("id.itemId", getImageItemId())).add(Restrictions.eq("id.callId", getCallID())).uniqueResult();
bImage = attachment.getFileData();
InputStream stream = new ByteArrayInputStream(bImage);
file = new DefaultStreamedContent(stream,externalContext.getMimeType(getFileName()),getFileName());
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
session.close();
}
}
public List<Attachment> getAttachmentList() {
return attachmentList;
}
public void setAttachmentList(List<Attachment> attachmentList) {
this.attachmentList = attachmentList;
}
public MyTeamService getService() {
return service;
}
public void setService(MyTeamService service) {
this.service = service;
}
public String getImageItemId() {
return imageItemId;
}
public void setImageItemId(String imageItemId) {
this.imageItemId = imageItemId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public DefaultStreamedContent getFile() {
return file;
}
public void setFile(DefaultStreamedContent file) {
this.file = file;
}
public String getCallID() {
return callID;
}
public void setCallID(String callID) {
this.callID = callID;
}
}
here dilogue opens correctly but image will not opened please help me.
I find it really weird I don't know why but when I first select an image it won't invoke the upload listener but at the second select it work perfectly.
View code :
<h:form enctype="multipart/form-data;charset='UTF-8'">
<p:fileUpload id="clientProfile" auto="true" sizeLimit="2097152" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" fileUploadListener="#{clientController.uploadListener}" mode="advanced" multiple="true" label="browse" update="imagePreview" invalidFileMessage="Invalid image" invalidSizeMessage="too large size"/>
<p:outputPanel id="imagePreview">
<ui:repeat value="#{clientController.listImages}" var="imageId">
<div style="float:left;margin-right:10px; margin-bottom: 5px;">
<p:graphicImage value="#{clientController.previewImage}" height="135" width="135" styleClass="images">
<f:param name="imageId" value="#{imageId}"/>
</p:graphicImage>
</div>
</ui:repeat>
</p:outputPanel>
</h:form>
Bean code :
private Map<UUID, UploadedFile> uploadedFiles = new HashMap<UUID, UploadedFile>();//used for preview
private List<String> listImages = new ArrayList<String>(); //list of id from map which is UUID
private List<UploadedFile> clientProfile = new ArrayList<UploadedFile>();
public void uploadListener(FileUploadEvent event) {
clientProfile.add(event.getFile());
final UUID uuid = UUID.randomUUID();
uploadedFiles.put(uuid, event.getFile());
listImages.add(uuid.toString());
System.out.println(listImages.size());
System.out.println(clientProfile.size());
}
public List<String> getListImages() {
return listImages;
}
public StreamedContent getPreviewImage() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
StreamedContent image = null;
String imageId = JsfUtil.getRequestParameter("imageId");
System.out.println(imageId);
if (imageId != null) {
UUID imageIndex = UUID.fromString(imageId);
return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFiles.get(imageIndex).getContents()));
}
}
return null;
}
I am using JSF 2.0 and PrimeFaces 3.0. I have uploaded the images and have to crop the image. The images are uploaded and successfully displayed in the upload pages.
When I select the images and click the crop button the corresponding crop bean is not called. If I don't select the image and click the crop button the corresponding crop bean class is called but a NullPointerException occurred. What is the problem?
The Facelet view is:
<h:form>
<p:panel header="FILE UPLOAD WITH CROPPER" style="width:900px; margin: 0 auto; margin-top:0px">
<p:fileUpload fileUploadListener="#{photoUploadAction.handleImageUpload}"
mode="advanced"
update="getImageId,messages" auto="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
<p:growl id="uploadMessages" showSummary="true" showDetail="true"/>
<h:panelGrid columns="2" >
<p:imageCropper value="#{photoUploadAction.croppedImage}" id="getImageId"
image="images/#{photoUploadVO.imageName}"/>
</h:panelGrid>
<p:commandButton value="Crop" update="getImageId" action="#{imageCropperBean.crop}" />
</p:panel>
</h:form>
BACKING BEAN for ImageCropper:
#ManagedBean(name="imageCrop")
#RequestScoped
public class ImageCropperBean {
private CroppedImage croppedImage;
private String newFileName;
private String imageName;
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
System.out.println("TEH IMAGE NAME ===="+imageName);
this.imageName = imageName;
}
public String getNewFileName() {
return newFileName;
}
public void setNewFileName(String newFileName) {
System.out.println("AAAAAAAAAAAAAA"+this.newFileName);
this.newFileName = newFileName;
}
public CroppedImage getCroppedImage() {
return croppedImage;
}
public void setCroppedImage(CroppedImage croppedImage) {
System.out.println("cRRRRRRRRRRRRR"+croppedImage);
this.croppedImage = croppedImage;
}
public ImageCropperBean(){
}
public String crop() {
System.out.println("WELCOMEMMMMMMMMMMMMMM");
FacesContext context = FacesContext.getCurrentInstance();
ImageCropperBean imageCropperBean = (ImageCropperBean) context.getApplication().evaluateExpressionGet(context, "#{imageCropperBean}", ImageCropperBean.class);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
newFileName = servletContext.getRealPath("") + File.separator + "cropImage" + File.separator+ "croppedImage.jpg";
System.out.println("FILE NAME NAME NAME NAME "+newFileName);
String file = new File(newFileName).getName();
System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"+file);
imageCropperBean.setImageName(file);
File fileFolder = new File("e:/Mecherie_project/image_web/WebContent/cropImages",file);
System.out.println("FILE ANE"+file);
// String target=null;
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(fileFolder);
System.out.println("HHHHHHHHHH=="+imageOutput);
imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
imageOutput.close();
FacesMessage msg = new FacesMessage("Succesful", file
+ " is cropped.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (FileNotFoundException e) {
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not Cropped!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not Cropped!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
// System.out.println("ghfhgfghgh"+target);
return "success";
}
}