javafile-uploadstruts2model-driven

Upload file Action class with ModelDriven in Struts 2


I'm studying Struts 2 and get an issue: cannot upload file in ActionClass that implements ModelDriven

Product.java

    public class Product {
    String name, image;

    public Product() {
    }

    public Product(String name, String image) {
        super();
        this.name = name;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

ProductAction.java

    public class ProductAction extends ActionSupport implements ModelDriven<Product> {

    private static final long serialVersionUID = -5538774764479904797L;

    File image;

    public void setImage(File file) {
        System.out.println("SET IMAGE");
    }

    public String submitPost() throws Exception {
        System.out.println(p.getName());
        System.out.println("POST");
        return SUCCESS;
    }

    Product p = new Product();

    @Override
    public Product getModel() {
        return p;
    }

}

I want to upload in ProductAction. But if ProductAction implements ModelDriven, method setImage() not called, and if ProductAction doesn't implement ModelDriven, it works normal. How can fix it?


Solution

  • Change the type of the image to File and getters/setters. When you use ModelDriven you don't need to use action properties. Action classes also known as controllers don't need to keep the state. Struts pushes your model to the top of the valueStack before populating it with request parameters.

    String name;
    File image; 
    //getters and setters