struts2文件上传(单文件)

index.jsp 

<s:form action="demo03/uploadfile" method="post" enctype="multipart/form-data"> 
    <s:file name="image" label="File"/>
    <s:submit/>
</s:form>


struts.xml

   

    <package name="default" namespace="/" extends="struts-default">
        <action name="uploadfile" class="cn.yang.action.UploadAction">
            <result name="success">
                <param name="location">/jsps/success.jsp</param>
            </result>
            <result name="input">
                <param name="location">/jsps/fail.jsp</param>
            </result>
            <!--配置上传文件拦截器-->
            <interceptor-ref name="fileUpload">
                <!--允许上传文件的类型-->
                <param name="allowedTypes">
                    text/plain
                </param>
                <!--允许上传文件的扩展名-->
                <param name="allowedExtensions">
                    .txt
                </param>
                <!--允许上传文件的最大容量-->
                <param name="maximumSize">
                    2097152000
                </param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"/>
        </action>
    </package>

UploadAction.java

    

    private File image;//上传文件存储的临时文件
    private String imageContenType;//此处格式固定(***+ContentType)
    private String imageFileName;//此处格式固定(***+FileName)
    public File getImage() {
        return image;
    }
    public void setImage(File image) {
        this.image = image;
    }
    public String getImageContenType() {
        return imageContenType;
    }
    public void setImageContenType(String imageContenType) {
        this.imageContenType = imageContenType;
    }
    public String getImageFileName() {
        return imageFileName;
    }
    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }
    @Override
    public String execute() throws Exception {
        ServletContext context = ServletActionContext.getServletContext();
        String path = context.getRealPath("/upload");
        File file = new File(path,imageFileName);
        FileUtils.copyFile(image,file);
        return SUCCESS;
    }


你可能感兴趣的:(struts2文件上传(单文件))