无法在java中上传文件

时间:2014-07-18 09:57:11

标签: java jsf file-upload jsf-2 richfaces

我使用的是richface和JSF。
我想上传具有特定路径的图像文件。
但它给我错误我的jsf页面如下

<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>

我的豆子

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();
        }
    }

错误就像这样

--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)

有什么问题?我没有遇到问题,我错了。感谢先进的帮助。

4 个答案:

答案 0 :(得分:0)

我认为问题出在

String filePath = "D:\\uploadImage"; File destFilePath = new File(filePath);

您将方向声明为文件,但您需要一个文件名才能写入特定文件。

例如尝试:

String filePath = "D:\\uploadImage"; File destFilePath = new File(filePath+"\\uploadimage.jpg");

答案 1 :(得分:0)

错误

  

java.io.FileNotFoundException:D:\ uploadImage(访问被拒绝)

非常清楚:找不到该文件。

引用您的代码:

File destFilePath = new File(filePath);
if (!destFilePath.exists()) {
    new File(filePath).mkdirs();
}
FileOutputStream fos = new FileOutputStream(destFilePath);
fos.write(buffer);

在您的特定情况下,您最初通过调用File#mkdirs()创建目录,然后尝试写入File对象引用的目录 。这是不合法的。

您需要创建文件并写入文件。例如,您可以使用Java SE 7 Files#copy(...)。另请参阅How to save uploaded file in JSF

答案 2 :(得分:0)

谢谢兄弟,我得到了答案。在第1行和第2行,我错了。我没有指定图像名称(文件名)

 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());
            }
        }

答案 3 :(得分:-1)

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