0

I have an issue with the file uploading in jsf. i have done the following code ih jsf .

index.xhtml(View)

<h:panelGrid columns="2">

            <h:outputLabel for="userId">User Id</h:outputLabel>
            <h:inputText id="userId" value="#{controller.user.userName}" required="true">                
            </h:inputText>

            <h:outputLabel for="username">Username</h:outputLabel>
            <h:inputText id="username" value="#{controller.user.userId}" required="true">               
            </h:inputText>

            <h:outputLabel for="photo">Profile Picture</h:outputLabel>
            <t:inputFileUpload value="#{controller.user.photo}"  required="true">                
            </t:inputFileUpload>

       </h:panelGrid>

User.java(model)

package com.profileapp.models;

import java.io.Serializable;
import org.apache.myfaces.custom.fileupload.UploadedFile;


public class User implements Serializable
{
    private String userId;
    private String userName;
    private UploadedFile photo;

    public User()
    {        
    }
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public UploadedFile getPhoto() {
        return photo;
    }

    public void setPhoto(UploadedFile photo) {
        this.photo = photo;
    }    
}

UserController.java(Controller)

package com.profileapp.controllers;

import com.profileapp.models.User;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.apache.commons.io.FilenameUtils;


@ManagedBean(name="controller")
@RequestScoped

public class UserController implements Serializable
{
    private User user=new User();   

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String submit() throws IOException ,SQLException ,ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        String fileName = FilenameUtils.getName(user.getPhoto().getName());
        byte[] bytes = user.getPhoto().getBytes();
        int index=fileName.indexOf('.');
        String extension=fileName.substring(index);
        File file;
        String path;
        path = "C:/Users/Manohar/Documents/NetBeansProjects/ProfileApplication/build/web/uploads/"+user.getUserName()+(float)Math.random()+"/";
        if(extension.equalsIgnoreCase(".jpg")||extension.equalsIgnoreCase(".jpeg")||extension.equalsIgnoreCase(".png")||extension.equalsIgnoreCase(".gif")||extension.equalsIgnoreCase(".tif"))
        {
            file=new File(path);      
            if(!file.exists())
            {
                file.mkdir();                
            }
            path=file+"/"+fileName;
            FileOutputStream outfile=new FileOutputStream(path);           
            outfile.write(bytes);
            outfile.close();  
            PreparedStatement stmt;            
            Connection connection;
            String url="jdbc:mysql://localhost:3306/userprofile";
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(url, "root", "mysql"); 
            stmt = connection.prepareStatement("insert into table_profile values('"+user.getUserName()+"','"+user.getUserId()+"','"+path+"')");                                 
            stmt.executeUpdate();
            connection.close(); 
            return "SUCCESS";
        }
        else
        {
            return "FAIL";
        }              
    }

}

when i run this code i gets a nullpointer execption for field inputFileUpolad element i.e. when i debug i observed that setter method of User.photo field not gets called

i got the following error (component tree)

<UIViewRoot id="j_id1" inView="true" locale="en_US" renderKitId="HTML_BASIC" rendered="true" transient="false" viewId="/index.xhtml">

    <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <UIOutput id="j_idt4" inView="true" rendered="true" transient="false">

        <title>Facelet Title</title>

    </UIOutput>

    <UIOutput id="j_idt6" inView="true" rendered="true" transient="false">

        <HtmlForm enctype="application/x-www-form-urlencoded" id="j_idt7" inView="true" prependId="true" rendered="true" submitted="true" transient="false">

            <HtmlPanelGrid border="-2147483648" columns="2" id="j_idt8" inView="true" rendered="true" transient="false">

                <HtmlOutputLabel escape="true" for="userId" id="j_idt9" inView="true" rendered="true" transient="false">

                    User Id

                </HtmlOutputLabel>

                <HtmlInputText disabled="false" id="userId" immediate="false" inView="true" localValueSet="false" maxlength="-2147483648" readonly="false" rendered="true" required="true" size="-2147483648" transient="false" valid="true" value="manu"/>

                <HtmlOutputLabel escape="true" for="username" id="j_idt11" inView="true" rendered="true" transient="false">

                    Username

                </HtmlOutputLabel>

                <HtmlInputText disabled="false" id="username" immediate="false" inView="true" localValueSet="false" maxlength="-2147483648" readonly="false" rendered="true" required="true" size="-2147483648" transient="false" valid="true" value="manu"/>

                <HtmlOutputLabel escape="true" for="photo" id="j_idt13" inView="true" rendered="true" transient="false">

                    Profile Picture

                </HtmlOutputLabel>

                <HtmlInputFileUpload disabled="false" id="j_idt15" immediate="false" inView="true" localValueSet="false" maxlength="-2147483648" readonly="false" rendered="true" required="true" size="-2147483648" transient="false" valid="true"/>

            </HtmlPanelGrid>

            <HtmlCommandButton action="#{controller.submit()}" actionExpression="#{controller.submit()}" disabled="false" id="j_idt16" immediate="false" inView="true" readonly="false" rendered="true" transient="false" type="submit" value="Register"/>

        </HtmlForm>

    </UIOutput>

    </html>

</UIViewRoot>
Manohar Bomma
  • 311
  • 1
  • 3
  • 17

1 Answers1

1

You forgot to properly set the form encoding to multipart/form-data. The JSF component tree shows that it's using the default of application/x-www-form-urlencoded.

Fix it accordingly:

<h:form enctype="multipart/form-data">

The default form enctype does namely not support file uploads. Don't forget to register the extensions filter in web.xml as per the manual. Otherwise JSF won't be able to properly execute the apply request values phase.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555