struts2-14文件上传

文件上传:
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、common-io-1.3.2.jar,这两个文件可以在http://commons.apache.org下载。
第二步:把form表单的enctype设置为“multipart/form-data”,如下:

<form enctype = "multipart/form-data" action = "${pageContext.request.contextPath}/xxxx.action" method = "post">
    <input type = "file" name = "uploadImages">
</form>

第三步:在Action中添加以下属性:(加*的部分要跟页面中file的name属性相同)

public class HelloWorldAction(){
    public File *uploadImages*;//获取上传的文件
    public String *uploadImages*ContextType;//获取文件的类型
    public String *uploadImages*FileName;//获取文件的名称

    //添加属性的getter/setter方法。

    public String uploads() throws Exception{
        String realPath = ServletActionContext.getServletContext().getRealPath("/images");
        File file = new File(realPath);
        if(!file.exists())
            file.mkdirs();
        FileUtils.copyFile(uploadImages,new File(file,uploadImagesFileName));
        return "success";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39660593/article/details/78819827