zoukankan      html  css  js  c++  java
  • struts2学习笔记(七)—— struts2的文件上传

    一、前台页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <!-- 注意!表单必须添加 enctype 属性,值为"multipart/form-data" -->
        <form action="upload.action" method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <input type="submit" value="上传"/>
        </form>
    </body>
    </html>

    前台页面要求:

    • 表单必须post提交
    • 表单提交类型enctype.必须多段式
    • 文件上传使用<input type="file" /> 组件

    二、后台

    public class UploadAction extends ActionSupport {
        // 上传的文件会自动封装到File对象
        // 在后台提供一个与前台input type=file组件name相同的属性
        private File file;
        // 在提交键名后加上固定后缀FileName,文件名称会自动封装到属性中
        private String fileFileName;
        // 在提交键名后加上固定后缀ContentType,文件MIME类型会自动封装到属性中
        private String fileContentType;
    
        public String upload(){
            if(file!=null){
                System.out.println("文件名称:"+fileFileName);
                System.out.println("文件类型:"+fileContentType);
                // 将上传文件保存到指定位置
                file.renameTo(new File("D:/upload/test3.jpg"));
            }
            
            return "success";
        }
    
        public void setFile(File file) {
            this.file = file;
        }
    
        public void setFileFileName(String fileFileName) {
            this.fileFileName = fileFileName;
        }
    
        public void setFileContentType(String fileContentType) {
            this.fileContentType = fileContentType;
        }
        
    }

    注意:这个fileFileName,fileContentType。如果File 属性名xxx(private File xxx;) 。那这个必须是xxxFileName, xxxContentType(否则将获取不到相应的值)。然后也是分别给set 方法就可以

  • 相关阅读:
    windows8安装docker(tool box)
    windows8 使用docker创建第一个nodejs运行环境
    nodejs使用fetch获取WebAPI
    Nodejs获取Azure Active Directory AccessToken
    使用Bot Service创建Bot Framework
    安装Team Services Agent Win7
    Nodejs微信与Bot framework通过Direct Line连接
    修改cmd默认启动路径
    less配置
    javascript滚动到大于一定距离显示隐藏
  • 原文地址:https://www.cnblogs.com/yft-javaNotes/p/10322843.html
Copyright © 2011-2022 走看看