zoukankan      html  css  js  c++  java
  • strut2 单个文件上传

    1. 第一步:在WEB-INF/lib下加载commons-fileupload-1.2.1.jar、commons-1.3.2.jar.这两个文件可从http://commons.apache.org/下载。
    2. 第二步:把from 表的enctype设置为:"multipart/form-data",如下:
      <from enctype="multipart/form-data" action="${pageContext.request.contextPath}/list.action" method="post"
            <input type="file" name="uploadImage">
      </form>
    3. 第三步:在action类中添加以下代码:
      package cn.itcast.action;
      
      import java.io.File;
      
      import org.apache.commons.io.FileUtils;
      import org.apache.struts2.ServletActionContext;
      
      import com.opensymphony.xwork2.ActionContext;
      
      
      public class HelloWorldAction {
          private File image;
          private String imageFileName;
          public String getImageFileName() {
              return imageFileName;
          }
          public void setImageFileName(String imageFileName) {
              this.imageFileName = imageFileName;
          }
          public File getImage() {
              return image;
          }
          public void setImage(File image) {
              this.image = image;
          }
          public String addUI(){
              return "success";
          }
      
          public String execute() throws Exception{
              
              String realpath = ServletActionContext.getServletContext().getRealPath("/images");//得到文件保存的目录(文件的绝对路径)
              System.out.println(realpath);
              if(image!=null){
                  File savefile = new File(new File(realpath), imageFileName);//savefile是一个完整的文件路径
                  if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();//如果保存文件的目录不存在则创建目录
                  FileUtils.copyFile(image, savefile);//调用系统函数拷贝文件image到savefile中
                  ActionContext.getContext().put("message", "上传成功");
              }
              return "success";
          }
      }

      4.struts.xml文件配置如下所示:

      <struts>
          <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
          <!--控制文件上传的大小-->
          <constant name="struts.multipart.maxSize" value="10701096"/>
          
          <package name="employee" extends="struts-default">
              <action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
                  <result name="success">/WEB-INF/page/message.jsp</result>
              </action>
          </package>
      </struts>
  • 相关阅读:
    交换机工作原理
    MyBatis框架的使用及源码分析(一) 配置与使用
    MySQL5.6安装步骤
    mysql创建用户,并授权
    命令行访问远程mysql数据库
    [mybatis] mybatis错误:Invalid bound statement (not found)
    【大数据】每秒十万笔交易的数据架构解读
    【mybaits】Mybatis中模糊查询的各种写法
    【redis】 linux 下redis 集群环境搭建
    [linux] linux下编译安装zlib
  • 原文地址:https://www.cnblogs.com/kailing-con/p/4196953.html
Copyright © 2011-2022 走看看