"Content-Disposition" Header shows wrong filename in dialog window "save as" - jsf

When I download a file, the filename that is display in the "save as" dialog window its the name of the view (Page2.pdf) and not the filename "cyn.pdf".
Header content disposition is on line 161 of FileUploadController and "download" its call on line 34 of Page2.xhtml
FileUploadController Bean
#ManagedBean(name = "fileUploadController")
#SessionScoped
public class FileUploadController implements Serializable {
private static final long serialVersionUID = 1L;
//tama�o del buffer
private static final int DEFAULT_BUFFER_SIZE = 10240;
private byte[] archi = new byte[0];
public String nombre;
public String ruta;
public String nombreArchivo;
public byte[] getArchi() {
return archi;
}
public void setArchi(byte[] archi) {
this.archi = archi;
}
// Nombre del Archivo
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRuta() {
return ruta;
}
public void setRuta(String ruta) {
this.ruta = ruta;
}
// ruta fisica del archivo
public String getRealPath() {
FacesContext aFacesContext = FacesContext.getCurrentInstance();
ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
return context.getRealPath("/");
}
/* subida del archivo con sus atributos */
public void fileUpload(FileUploadEvent event, String nombre, String type, String directorio) {
try {
this.nombre = "cyn" + type;
this.ruta = directorio + getNombre();
this.archi = getFileContents(event.getFile().getInputstream());
File file = new File(directorio);
nombreArchivo = file.getName();
// Crea el directorio, incluidos subdirectorios q no existan
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception ex) {
System.out.println("Error en la subida " + ex);
}
}
private byte[] getFileContents(InputStream in) {
byte[] bytes = null;
try {
// write the inputStream to a FileOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
bos.write(bytes, 0, read);
}
bytes = bos.toByteArray();
in.close();
in = null;
bos.flush();
bos.close();
bos = null;
} catch (IOException e) {
System.out.println(e.getMessage());
}
return bytes;
}
// Guardar el archivo
public void guardar() {
try {
FileOutputStream out;
out = new FileOutputStream(ruta);
System.out.print("out" + out);
out.write(archi);
System.out.print(archi);
out.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
/*-------------------- Servlet Descarga Archivos----------------------------------------------*/
public void downLoad() throws IOException, ServletException {
FacesContext contexto = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) contexto.getExternalContext().getResponse();
//ruta de los archivos
System.out.println("paso parametro ruta " + ruta);
File file = new File(ruta);
System.out.println("paso parametro ruta a file " + file);
/*Validacion*/
if (!file.exists()) {
System.out.println("El archivo no existe!");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/pdf");
response.setHeader("Content-Length", String.valueOf(file.length()));
/*Ventana de abrir/guardar*/
/*attachment: muestra la ventana*/
response.setHeader("Content-Disposition", "attachment; Nombre del Archivo=\"" + nombreArchivo + "\"");
System.out.println("NOmbre archivo en download" + nombreArchivo);
//inicializo el input y el output
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
//cierro
input.close();
output.close();
}
contexto.responseComplete();
}
}
View: Page2.xhtml
<h:body>
<h2>Acceso Alumno</h2>
<h1>Alumnos registrados </h1>
<h:form>
<h:dataTable id ="tabla" value ="#{alumno.getListaAlumno()}" var= "var" border="1">
<h:column>
<f:facet name="header">Id </f:facet>
<h:outputText value = "#{var.id}"/>
</h:column>
<h:column>
<f:facet name="header">Nombre y Apellidos </f:facet>
<h:outputText value = "#{var.nombreApellidos}"/>
</h:column>
<h:column>
<f:facet name="header">Matricula </f:facet>
<h:outputText value = "#{var.matricula}"/>
</h:column>
<h:column>
<f:facet name="header">ProductBox </f:facet>
<h:commandButton action="#{fileUploadController.downLoad}" value="Guardar Archivo" >
<f:setPropertyActionListener target="#{fileUploadController.ruta}" value="#{var.pdf}" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
<h:form>
<h:commandButton action="home?faces-redirect=true" value="Home" />
</h:form>
<!-- Cerrar Sesion -->
Cerrar Sesion
</h:body>
</html>

Try using the following Content-disposition
response.setHeader("Content-disposition", "attachment;filename=cyn.pdf");

Related

Display list of images using p:graphicImage in p:dataGrid after uploading image through p:fileUpload

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 ?

Apachce tomcat/7.0.30 Http status 404 error while downloading the file

I am try to downloading the file using JSF by giving table attributes as a path when I run program it works fine once and after that error comes HTTP status 404... what should I do to download the file?
XHTML code
<p:dataTable id="idAttachmentTable" var="attach"
value="#{documentMB.attachList1}"
selectionMode="single"
selection="#{documentMB.selectedAttachment}"
rowKey="#{attach.attachmentId}">
<f:facet name="header">
Attachments
</f:facet>
<p:column headerText="#{bundle.subject}">
<h:outputText value="#{attach.attachName}" />
</p:column>
<p:column>
<h:commandLink id="getDownload" value="#{attach.attachName}" action="#{documentMB.downLoad}">
<f:setPropertyActionListener target="#{documentMB.selectedAttachment}" value="#{attach}" />
</h:commandLink>
</p:column>
</p:dataTable>
documentMb.java
private static final int DEFAULT_BUFFER_SIZE = 10240;
private String filePath = "C:\\temp\\123.PNG";
public void downLoad() throws IOException {
System.out.println("in download");
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
System.out.println("after Faces");
System.out.println(filePath);
System.out.println(selectedAttachment.getAttachmentName());
java.io.File file = new java.io.File(selectedAttachment.getAttachmentName());
System.out.println(selectedAttachment.getAttachmentName());
if (!file.exists()) {
System.out.println(selectedAttachment.getAttachmentName());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
System.out.println(file.getName());
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
input.close();
output.close();
}
context.responseComplete();
}

rendered attribute not working with request parameter

I am using JSF2.2 with primefaces 5.0. I have a xhtml file where there are two file Uploads where one should always be visible while other should be visible only when request parameter, named signmethod, is JAVAME.
<h:panelGrid>
<h:panelGroup>
<h:outputLabel for="selected_signmethod" value="Selected Signethod : "/>
<h:outputText id="selected_signmethod" value="#{param.signmethod}" />
</h:panelGroup>
<h:panelGroup>
<b>Select file(s) to upload:</b>
</h:panelGroup>
</h:panelGrid>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:message for="file_upload"/>
<p:fileUpload id="file_upload" allowTypes="#{fileUploadView.allowedTypes}" label="Select file" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" update="growl" multiple="true" fileLimit="5"/>
<p:message for="javame_upload"/>
<h:panelGroup rendered="#{param.signmethod == 'JAVAME'}" >
<b>Select corresponding jar file(s) to upload:</b>
<p:fileUpload id="javame_upload" allowTypes="" label="Select Jar file for javame" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" multiple="true" fileLimit="5"/>
</h:panelGroup>
<p:commandButton ajax="false" id="signProceed" value="Proceed" action="#{fileUploadView.submit}"/>
</h:form>
But this seems to be not happening. Second upload component is not getting rendered at all. I am also printing value of param.signmethod so that to be sure that right value is getting into param.signmethod, which is correct. So whats stopping this component to get rendered.
Managed Bean code :
#ManagedBean
#ViewScoped
public class FileUploadView implements Serializable {
#ManagedProperty(value = "#{signBundleBean}")
private SignBundleBean signBundleBean;
static String uploadDirRoot = InitialisationHelper.getUploadDirRoot();
transient Map<String, Object> sessionMap;
ArrayList<Signing> signings;
String username;
SignMethod signMethod;
public FileUploadView() {
System.out.println("NEW FileUploadView created.");
}
#PostConstruct
public void init() {
System.out.println("#POstConstruct FileuploadView");
System.out.println("signMethod : " + signMethod);
sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
signings = signBundleBean.getSignings();
username = (String) sessionMap.get("username");
}
public void handleFileUpload(FileUploadEvent e) {
String signId = "" + DatabaseHelper.genrateSigningId();
FacesContext ctx = FacesContext.getCurrentInstance();
UploadedFile uploadedFile = e.getFile();
String filename = uploadedFile.getFileName();
if (signId.equals("-1")) {
FacesMessage fm = new FacesMessage();
fm.setDetail("Database Connection not working. Please try later.");
fm.setSummary("DBConnection_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
//ctx.addMessage(null, fm);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
if (username == null) {
FacesMessage fm = new FacesMessage();
fm.setDetail("You are not in session to upload.");
fm.setSummary("Session_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
Signing sg;
sg = new Signing(signId, username, filename, signMethod, false);
signings.add(sg);
System.out.println("Signing added : " + sg);
signBundleBean.setMaxParameters(SignParametersInitialisation.getNumberOfParameters(signMethod));
try {
InputStream is = uploadedFile.getInputstream();
OutputStream os = new FileOutputStream(sg.getUploadfile());
byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
sg.setUploaded(true);
is.close();
os.close();
} catch (IOException ex) {
signings.remove(sg);
Logger.getLogger(FileUploadView.class.getName()).log(Level.SEVERE, null, ex);
}
FacesMessage fm = new FacesMessage();
fm.setDetail(filename);
fm.setSummary("FileUploaded");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
//ctx.addMessage(null, fm);
ctx.addMessage(null, fm);
System.out.println(sg + " File uploaded to " + sg.getUploadfile());
}
}

Failed to parse the expression [#{privilegeManagedBean.deleteAction(p)}]

I want to delete selected row from data table when click on GraphicImage under CommandLink.
but it is don't work for me.
it gives error :-
/privilegepage.xhtml #66,21 action="#{privilegeManagedBean.deleteAction(p)}" Failed to parse the expression [#{privilegeManagedBean.deleteAction(p)}]
Bean:-Privilege
public class Privilege {
private int id;
private String privilege;
public Privilege() {
}
public Privilege(int id, String privilege) {
this.id = id;
this.privilege = privilege;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
}
bean:- PrivilegeDao.java
public int deletePrivilege(int id) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "delete privilege from privilege where id=?";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setInt(2, id);
if(preparedStatement.executeUpdate()==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is delete :- ");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}
bean :-PrivilegeManagedBean
#ManagedBean(name = "privilegeManagedBean", eager = true)
#SessionScoped
/* #ManagedProperty(value="#param.id") */
public class PrivilegeManagedBean {
private int id;
private String privilege;
private PrivilegeDao pdao;
#SuppressWarnings("unused")
private List<Privilege> privilegeData;
private static int srno;
private int selectedRowIndex = -1;
public PrivilegeManagedBean() {
privilegeData = new ArrayList<Privilege>();
pdao = new PrivilegeDao();
srno = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
public void setPrivilegeData(List<Privilege> privilegeData) {
this.privilegeData = privilegeData;
}
public List<Privilege> getPrivilegeData() {
return this.privilegeData = pdao.getUserList();
}
public int getSelectedRowIndex() {
return selectedRowIndex;
}
public void setSelectedRowIndex(int selectedRowIndex) {
this.selectedRowIndex = selectedRowIndex;
}
public void addDataTableRow() {
pdao.addRow(this.id, this.privilege);
}
private static ArrayList<Privilege> privilegeList = new ArrayList<Privilege>();
public ArrayList<Privilege> getPrivilegeList() {
return privilegeList;
}
public void setPrivilegeList(ArrayList<Privilege> privilege) {
privilegeList = (ArrayList<Privilege>) pdao.getUserList();
}
public int addAction() {
Privilege privilegeitem = new Privilege(this.id, this.privilege);
privilegeList.add(privilegeitem);
return pdao.addPrivilege(this.privilege);
}
public int deleteAction() {
Privilege privilegeitem = new Privilege(this.id, this.privilege);
privilegeList.remove(privilegeitem);
System.out.println("delete Action...");
return pdao.deletePrivilege(this.id);
}
public int onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Privilege Edited",
((Privilege) event.getObject()).getPrivilege());
FacesContext.getCurrentInstance().addMessage(null, msg);
int pid = pdao.getPrivilegeId(this.privilege);
System.out.println("Privilege Name For Id :- " + this.privilege);
System.out.println("Privilege Id :- " + pid);
return pdao.updatePrivilege(pid, this.privilege);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Privilege Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
privilegeList.remove((Privilege) event.getObject());
}
public String deletePrivilege(Privilege privilege) {
privilegeList.remove(privilege);
return null;
}
public int getSrno() {
return ++srno;
}
}
Privilege.xhtml
<p:growl id="messages" showDetail="true" />
<p:dataTable value="#{privilegeDao.userList}" var="p"
id="datatbldispprivilege" style="width:500px" editable="true" lazy="true">
<f:facet name="header">
Privilege List
</f:facet>
<p:ajax event="rowEdit" listener="#{privilegeManagedBean.onEdit}"
update=":form1:messages" />
<p:ajax event="rowEditCancel"
listener="#{privilegeManagedBean.onCancel}" update=":form1:messages" />
<p:column headerText="Privileges Name">
<p:cellEditor>
<f:facet name="output">
<p:outputLabel value="#{p.privilege}" name="privilegeoutputname" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{privilegeManagedBean.privilege}"
name="privilegeinputname" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options" style="width:100px">
<p:rowEditor>
</p:rowEditor>
</p:column>
<p:column headerText="Delete" style="width:100px">
<p:commandLink action="#{privilegeManagedBean.deleteAction(p)}"
update="#form">
<p:graphicImage value="/images/deleteicon.png" library="images"
onclick="if (!confirm('Are you sure you want to delete the current record?')) return false"
width="20px" height="20px" />
<f:param name="pname" value="#{p.name}" />
</p:commandLink>
</p:column>
</p:dataTable>
Your PrivilegeManagedBean#deleteAction don't accepts any arguments, but your JSF code passes the current iteration of the data table value to the method. So either don't pass anything to the method:
<p:commandLink action="#{privilegeManagedBean.deleteAction()}" update="#form">
or change the method signature of PrivilegeManagedBean#deleteAction.
you're trying to call the wrong method. action should be like this:
<p:commandLink action="#{privilegeManagedBean.deletePrivilege(p)}" update="#form">

Navigation to call action for bean class

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";
}
}

Resources