问题
I am using richface and JSF .
I want to upload the image file with specific path .
But it give me error My jsf page is as follows
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
<ui:define name="header-title">
<h:panelGroup id="headerPanelGroup">
<span>Create New User</span>
</h:panelGroup>
</ui:define>
<ui:define name="content">
<h:form id="newUserForm" prependId="false">
<div id="mainDiv">
<div>
<rich:panel id="userPanel">
<h:panelGroup>
<h:panelGrid columns="2">
<span>Upload Photo</span>
<rich:fileUpload fileUploadListener="#{newUserBean.photoListener}" id="uploadPhoto"
style="height: 120px !important;" maxFilesQuantity="5">
<a4j:ajax event="uploadcomplete" execute="@none" render="info" />
</rich:fileUpload>
</h:panelGrid>
</h:panelGroup>
</rich:panel>
</div>
</div>
<div>
<a4j:commandButton id="saveBtn" value="Submit" action="#{newUserBean.insertEmployeeData}" />
</div>
</h:form>
</ui:define>
</ui:composition>
My Bean
public void photoListener(FileUploadEvent event) throws Exception {
UploadedFile item = event.getUploadedFile();
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
String destPath = session.getServletContext().getRealPath("/");
// String destPath = str.substring(0, str.substring(0, str.lastIndexOf(File.separator))
// .lastIndexOf(File.separator) + 1);
String filePath = "D:\\uploadImage";
File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
new File(filePath).mkdirs();
}
try {
// InputStream inputstrem = new FileInputStream(new File(filePath));
// getNewUserVO().setInputstrem(inputstrem);
InputStream stream = item.getInputStream();
long fSize = item.getSize();
int lastIndex = item.getName().lastIndexOf(".");
String fileExtension = item.getName().substring(lastIndex);
System.out.println("--destPath--" + filePath + "--" + fSize + "--" + fileExtension + "----"
+ fileExtension.equalsIgnoreCase("jpg"));
if (!fileExtension.equalsIgnoreCase(".jpg")) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_001"),
null));
} else if (fSize > 102400) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_002"),
null));
} else {
FileOutputStream fos = new FileOutputStream(destFilePath);
byte[] buffer = new byte[(int) fSize];
stream.read(buffer, 0, (int) fSize);
stream.close();
fos.write(buffer);
fos.close();
}
} catch (FileNotFoundException e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_003"), null));
e.printStackTrace();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_004"), null));
e.printStackTrace();
}
}
Error comes like this
--destPath--D:\uploadImage--5416--.jpg----false
java.io.FileNotFoundException: D:\uploadImage (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at com.fractal.fms.modules.newUser.NewUserBean.photoListener(NewUserBean.java:167)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.richfaces.event.MethodExpressionEventListener.processEvent(MethodExpressionEventListener.java:125)
at org.richfaces.view.facelets.FileUploadHandler$FileUploadListenerImpl.processFileUpload(FileUploadHandler.java:55)
at org.richfaces.event.FileUploadEvent.processListener(FileUploadEvent.java:48)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:771)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:751)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:927)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:137)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Jul 18, 2014 3:06:59 PM org.richfaces.request.MultipartRequest25 release
SEVERE: File delete failed
java.io.IOException: File delete failed
at org.richfaces.request.FileUploadDiscResource.delete(FileUploadDiscResource.java:74)
at org.richfaces.request.UploadedFile25.delete(UploadedFile25.java:54)
at org.richfaces.request.MultipartRequest25.release(MultipartRequest25.java:163)
at org.richfaces.context.FileUploadFacesContextFactory$FileUploadFacesContext.release(FileUploadFacesContextFactory.java:70)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:612)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:137)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
What is wrong? I am not getting the problem where I am going to wrong .Thanks for the help in advanced.
回答1:
I think the issue is in the
String filePath = "D:\\uploadImage";
File destFilePath = new File(filePath);
you are declaring a direction as a file, but you need a filename to write to a specific file.
for example try:
String filePath = "D:\\uploadImage";
File destFilePath = new File(filePath+"\\uploadimage.jpg");
回答2:
The error
java.io.FileNotFoundException: D:\uploadImage (Access is denied)
is quite clear: the file is not found.
To quote from your code:
File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
new File(filePath).mkdirs();
}
FileOutputStream fos = new FileOutputStream(destFilePath);
fos.write(buffer);
In your particular case you are initially creating a directory by calling File#mkdirs() and later trying write to the directory referenced by that File
object. This is not legal.
You need to create a file and write to the file instead. For instance, you could use Java SE 7 Files#copy(...). See also How to save uploaded file in JSF.
回答3:
Thanks brother , I got the answer. at line 1 and line 2 where I am going to wrong. I was not specify the image name (file name)
public void photoListener(FileUploadEvent event) throws Exception {
UploadedFile item = event.getUploadedFile();
String fileName = "";
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
String destPath = session.getServletContext().getRealPath("/");
// String destPath = str.substring(0, str.substring(0, str.lastIndexOf(File.separator))
// .lastIndexOf(File.separator) + 1);
String filePath = destPath + "/UserInfo/" + getNewUserVO().getName();
File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
new File(filePath).mkdirs();
}
try {
InputStream stream = item.getInputStream();
long fSize = item.getSize();
int lastIndex = item.getName().lastIndexOf(".");
String fileExtension = item.getName().substring(lastIndex);
if (!fileExtension.equalsIgnoreCase(".jpg")) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_001"),
null));
} else if (fSize > 102400) {
FacesContext.getCurrentInstance().addMessage(
"",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_002"),
null));
} else {
System.out.println("user name--" + getNewUserVO().getName());
fileName = getNewUserVO().getName() + fileExtension;
filePath = destFilePath + File.separator + fileName; // line 1
FileOutputStream fos = new FileOutputStream(filePath); // line 2
byte[] buffer = new byte[(int) fSize];
stream.read(buffer, 0, (int) fSize);
stream.close();
fos.write(buffer);
fos.close();
getNewUserVO().setPhotoPath(filePath);
}
} catch (FileNotFoundException e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_003"), null));
log.info(e.getMessage());
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage("",
new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsgBundle.getString("NEWUSER_BEAN_004"), null));
log.info(e.getMessage());
}
}
回答4:
package com.journaldev.servlet;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FileLocationContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists())
file.mkdirs();
System.out.println("File Directory created to be used for storing files");
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}
来源:https://stackoverflow.com/questions/24822211/unable-to-upload-the-file-in-java