java 文件上传 struts2.0实现

Posted yimian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 文件上传 struts2.0实现相关的知识,希望对你有一定的参考价值。

1. web.xml  写全文拦截器

WEBROOT--- WEB-INF ---- WEB.XML

<filter>
<filter-name>Struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

2.写个文件上传页面

WEBROOT--E文件夹下----- upload.jsp

  <body>
          <form action="${pageContext.request.contextPath }/fileuploadaction" method="post" enctype="multipart/form-data">
          用户名:<input type="text" name="username"><br/>
          文件:<input type="file" name="file1"><br/>
          <input type="submit" value="上传">
      </form>
  </body>

 

3. 项目文件下     struts.xml

<struts>

    <!-- 二、总配置文件:引入其他所有配置文件 -->
    

    <include file="cn/itcast/e_fileupload/upload.xml"></include>
    
</struts>

 

4.  项目src下   建立包: cn.itcast.e_fileupload      下 新建  upload.xml

  

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="upload_" namespace="/" extends="struts-default"   abstract="false">
<action name="fileuploadaction"  class="cn.itcast.e_fileupload.fileupload"  >
<result name="success">/e/success.jsp</result>
</action>
</package>
</struts>

 

 

5. cn.itcast.e_fileupload 下新建 fileupload.java

package cn.itcast.e_fileupload;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class fileupload extends ActionSupport{
    private File file1;
    private  String file1FileName;          //该变量 固定格式   "file1" + FileName(注意大小写) 
    private String file1ContextType;        //该变量 固定格式   
    public void setFile1(File file1) {
        this.file1 = file1;
    }
    public void setFile1filename(String file1FileName) {
        this.file1FileName = file1FileName;
    }
    public void setFile1contexttype(String file1ContextType) {
        this.file1ContextType = file1ContextType;
    }
    @Override
    public String execute() throws Exception {
        String path=ServletActionContext.getServletContext().getRealPath("/upload");
        File desfile=new File(path,file1FileName);
        FileUtils.copyFile(file1, desfile);
             return SUCCESS;
    }

}

 

以上是关于java 文件上传 struts2.0实现的主要内容,如果未能解决你的问题,请参考以下文章

springboot报错说 Failed to parse multipart servlet request; nested exception is java.io.IOException(代码片

批量上传

java实现图片上传至服务器并显示,如何做?希望要具体的代码实现

LeetCode-面试算法经典-Java实现106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)(示例(代码片

java如何实现文件上传和下载的功能

Java利用JSch实现sftp通过ssh上传下载删除文件及配置代码