strut2 加 common-fileuplad组件做文件上传

今天用strut2 加 common-fileuplad组件做文件上传,遇到了点问题,后来百度解决,总结如下:


前台界面写在jsp中:

<form class="fileupload-buttonbar" action="UploadAction!upload.action" enctype="multipart/form-data" method="post">
        <input class="fileinput-button" type="file" name="uploadfile" id="file" />
        <br>
        <input class="btn btn-primary btn-lg btn-block" type="submit" value="上传"/>
    </form>


后台处理在继承自ActionSurpport的Action中(以下为主要属性和方法):

private File uploadfile;
    private String uploadfileFileName ;
    private String uploadfileContextType;

    public String upload() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        //文件类型
        String fileType = uploadfileFileName.substring(uploadfileFileName.lastIndexOf(".") + 1);
        //文件保存目录路径
        String savePath = ServletActionContext.getServletContext().getRealPath("/") + "FileDir/";
        //检查文件保存目录路径
        UploadFileKit ufk = new UploadFileKit(new File(savePath));
        if(!ufk.checkUploadDir()) {
            return ERROR;
        }

        try {
            FileUtils.copyFile(uploadfile, new File(savePath, UploadFileKit.getFileName(fileType)));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }                         seter and geter …………


注意彩色部分:  文件上传控件的name属性值要和action的属性对应起来,例如: <input type="file" name="a">  则 action中的属性要是这样  

private  File a;

private String aFileName;

private String aContextType;


你可能感兴趣的:(struts2,upload)