zoukankan      html  css  js  c++  java
  • struts2文件上传需要注意的

    ① 必须封装三个字段:文件、文件类型、文件名,而且这三个字段的名字的前面几个字母是一样的

      如:

    private File upload;
    private String uploadContentType;
    private String uploadFileName;

    由File名upload,确定了文件类型这个字段的名字必须为uploadContentType,不能是upContentType,不能是upcontenttype

    由File名upload,确定了文件名这个字段的名字必须为uploadFileName,不能是upFileName,不能是uploadfilename

    如果你的File名是uploadFile那么确定了:uploadFileContentType, uploadFileFileName

    <s:form action="up" enctype="multipart/form-data">
        <s:file name="upload" label="选择文件"/><br/>
        <s:submit value="上传"/>
    </s:form>

    注意form的enctype属性为multipart/form-data,file的name属性要和Action类中的file字段的名字一致

    ③ 可以配置savePath:

    /*****方法一: Annotation******/
    @Action(params={"savePath", "/uploadFiles"})
    
    
    
    
    
    
    /****方法二: struts.xml********/
    <action name="up" class="com.xxx.action.UpAction">
        <!-- 动态设置Action的属性值 -->
        <param name="savePath">/uploadFiles</param>
        <!-- 配置Struts 2默认的视图页面 -->
        <result>/WEB-INF/content/succ.jsp</result>    
    </action>

    然后在Action中加入setSavePath(正常,略)和getSavePath():

    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    ④ 读取文件和写入文件(包括生成文件夹):

      

    public String execute() throws Exception {
        //生成文件夹
        File filePath = new File(getSavePath());
        if (!filePath.exists()) {
            filePath.mkdirs();
            System.out.println("mkdirs");
        }
        //以服务器的文件保存地址和原文件名建立上传文件输出流
        FileOutputStream fos = new FileOutputStream(getSavePath()
            + "\" + getUploadFileName());
        FileInputStream fis = new FileInputStream(getUpload());
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) > 0) {
            fos.write(buffer , 0 , len);
        }
        fos.close();
        return SUCCESS;
    }

    注意实例化FileOutputStream时,构造参数的"\",忘了这个文件名就和路径连接在一起了

     

  • 相关阅读:
    使用Apache Commons-email邮件客户端发邮件
    Jfinal开发代码碎片_导出报表_配置druid数据源_使用guava_获取当前操作系统_JDK版本_jfinal-utils_jfinal验证码
    Memcached缓存集群_创建多实例
    HttpClient取得自定义的状态码302,并获取Header中的参数Location
    对象序列化和反序列化
    【校园电子书城】测试及部署
    mysql导入txt文件
    【校园电子书城】部分代码及数据库设计
    【校园电子书城】需求分析
    Domain logic approaches
  • 原文地址:https://www.cnblogs.com/lanhj/p/3381401.html
Copyright © 2011-2022 走看看