IE9中的jsf文件上传问题

时间:2012-08-08 09:03:44

标签: hibernate file-upload jsf-2 primefaces

我正在使用带有primefaces的jsf2.0 ..在我的应用程序中,我有图像上传选项。文件上传工作正常除了IE9以外的所有浏览器..当我尝试在IE9上传文件时我没有上传,我收到以下错误。

堆栈跟踪

java.io.FileNotFoundException: D:\Eclipse_wspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ChennaiVolunteer\activityPhoto\C:\Users\Public\Pictures\Sample Pictures\Desert.jpg (The filename, directory name, or volume label syntax is incorrect)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at com.chennaivolunteer.photo.upload.PhotoUploadAction.handleImage(PhotoUploadAction.java:188)
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:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
at org.primefaces.component.fileupload.FileUpload.broadcast(FileUpload.java:298)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:937)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:269)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1249)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:682)
at org.apache.myfaces.lifecycle.ApplyRequestValuesExecutor.execute(ApplyRequestValuesExecutor.java:34)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:77)
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:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:185)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
 Aug 8, 2012 2:24:16 PM org.apache.catalina.core.StandardWrapperValve invoke

SE

我的image.xhtml是

<f:view>
        <h:form  enctype="multipart/form-data">
            <p:panel  header="Event Images" style="font-size:12px;height:499px">
            <h:inputHidden value="#{photoUploadAction.aid}"></h:inputHidden>
            <p:messages id="messages" for="imaload"></p:messages>       
             <p:fileUpload id="imaload" fileUploadListener="#{photoUploadAction.handleImage}"  
                           mode="advanced"  multiple="true"
                          update="messages"  
                           immediate="true"  
                           allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>  
                 <!--  <p:growl life="1000"  id="messages"/>  --> 
            </p:panel>
        </h:form>
    </f:view>

我的支持bean方法是

    public void handleImage(FileUploadEvent event) throws IOException {
        BufferedImage bufferedImage;
        // setAid(getAid());

        String tmpFile = scontext.getRealPath(("/activityPhoto/")
                + event.getFile().getFileName());

        //File realPath = new File("e:/cv_project/ChennaiVolunteer/WebContent/activityPhoto",(event.getFile().getFileName()));
        File realPath = new File("d:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/ChennaiVolunteer/activityPhoto",(event.getFile().getFileName()));

        String filName = realPath.toString();

        /*File result = new File(tmpFile);

        String exactPath = result.toString();
*/
        byte[] imageByte = event.getFile().getContents();

        boolean flag = false;

        //storeImage(imageByte, tmpFile);

        String images = event.getFile().getFileName();
        photoUploadVO.setImageName(images);

        imageName = photoUploadVO.getImageName();

        if (loginBean.getType().equals("admin")
                || loginBean.getType().equals("ngo_coordinator")
                || loginBean.getType().equals("ngo")) {

            if (ngoPojo.getNgo_id() != 0) {
                photoUploadVO.setUsrId(ngoPojo.getNgo_id());
                photoUploadVO.setPhotoStatus("valid");
                photoUploadVO.setReasonForReject("pending");
                photoUploadVO.setUser_type(ngoPojo.getType());

            } else {
                photoUploadVO.setUsrId(loginBean.getUser_id());
                photoUploadVO.setPhotoStatus("valid");
                photoUploadVO.setReasonForReject("pending");
                photoUploadVO.setUser_type(loginBean.getType());
            }
        } else {
            photoUploadVO.setUsrId(loginBean.getUser_id());
            photoUploadVO.setPhotoStatus("pending");
            photoUploadVO.setReasonForReject("pending");
            photoUploadVO.setUser_type(loginBean.getType());
        }

        photoUploadVO.setCreated_by(loginBean.getEmail());
        photoUploadVO.setCreatedDate(new Date());
        photoUploadVO.setPhoto_path(tmpFile);
        InputStream in = new ByteArrayInputStream(imageByte);

        // photoUploadVO.setUsrId(loginBean.getUser_id());
        // photoUploadVO.setActivityId(getAid());
        bufferedImage = ImageIO.read(in);


        if (bufferedImage.getWidth() <= 400 && bufferedImage.getHeight() <= 400) {

            photoUploadVO.setDisabled("false");
            getMthd(imageByte, tmpFile);

        } else {

            try {
                photoUploadVO.setDisabled("false");

                //BufferedImage image = ImageIO.read(in);
                ImageIO.write(resize(bufferedImage, 400, 400), "jpg", new File(tmpFile));
                flag = photoUploadDaoService.uploadPhotos(photoUploadVO);

                // profileImageService.uploadPhotos(profileImageBean);
                if (flag == true) {
                    FacesMessage msg=null;
                    if(loginBean.getType().equals("admin")) {
                     msg = new FacesMessage("Successfully Uploaded");
                    }
                    if(!loginBean.getType().equals("admin")) {
                         msg = new FacesMessage("Successfully Uploaded(After administrator approve your photos will display on portal)");
                        }

                    FacesContext.getCurrentInstance().addMessage(null, msg);
                } else {
                    FacesMessage msg = new FacesMessage("Failure", event
                            .getFile().getFileName() + " to uploaded.");

                    FacesContext.getCurrentInstance().addMessage(null, msg);
                }

            } catch (IOException e) {
                e.printStackTrace();

                FacesMessage error = new FacesMessage(
                        FacesMessage.SEVERITY_ERROR,
                        "The files were not uploaded!", "");
                FacesContext.getCurrentInstance().addMessage(null, error);
            }

        }

    }

提前致谢。

1 个答案:

答案 0 :(得分:3)

这是由IE中的安全漏洞引起的。所有IE版本都发送完整的客户端文件路径,而不仅仅是文件名和上传文件。

您应该使用Commons IO FilenameUtils#getName()从完整的客户端文件路径中提取文件名,然后再在代码中使用它。

String filename = FilenameUtils.getName(event.getFile().getFileName()));
// ...

另见:


对具体问题

无关,整个tmpFile变量是多余的。到目前为止,您在代码中根本不需要它。完全摆脱它。这也是创建临时文件的错误方法。 getRealPath()可能会在某些服务器配置中返回null,并且绝对不想保存文件,只能从中读取文件。