Struts 2 file upload : File object being null

前端 未结 2 492
南旧
南旧 2020-12-20 06:32

I am trying to use Struts 2 file upload but it seems to me that its not working. Below is my code.

UploadAction.java:

public class Uploa         


        
相关标签:
2条回答
  • 2020-12-20 07:02

    Apart from changing the saveDir (really not necessary, and dangerous), your are not following the conventions in the Action class: the name of an private variable must match the names of its Getters and Setters; and finally, in page you are mismatching the name by pointing to the private variable, not the setter. Change it to:

    public class UploadAction extends ActionSupport{
    
        private File   upload;
        private String uploadFileName;
        private String uploadContentType;
    
        public void setUpload(File upload){
            this.upload=upload;
        }
        public void setUploadContentType(String uploadContentType){
            this.uploadContentType=uploadContentType;
        }
        public void setUploadFileName(String uploadFileName){
            this.uploadFileName=uploadFileName;
        }
    
        @Override
        public String execute(){
            if(upload==null)
            {
                System.out.println("No file....");
            }
            System.out.println(uploadContentType);
            System.out.println(uploadFileName);
            return SUCCESS;
        }
    }
    

    JSP

    <s:form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="upload" id="uploadfile" />
        <input type="submit" id="submit" />
    </s:form>
    
    0 讨论(0)
  • 2020-12-20 07:22

    Change this

            <input type="file" name="file" id="uploadfile" />
    

    to

            <input type="file" name="upload" id="uploadfile" />
    

    Your setter in your action class is setUpload so it is looking for a request parameter called upload, not file. For the sake of convention you should also change

    private File file;
    
    public void setUpload(File file){
        this.file=file;
    }
    

    to

    private File upload;
    
    public void setUpload(File file){
        this.upload=file;
    }
    
    0 讨论(0)
提交回复
热议问题