Struts2文件上传和文件下载

一、前言

  由于Struts2框架对上传组件进行了封装,使得文件上传的实现简单。

  在Struts2框架中提供对commons-fileupload组件的支持,并且默认使用该组件实现文件上传。因此,为了实现文件上传功能,我们需要在项目中包含如下两个jar文件:

  commons-fileupload-x.x.x.jar、commons-io-x.x.x.jar  注意:jar文件版本取决于当前工程使用的Struts2的版本。

二、实现文件上传

1)上传页面的准备

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>文件上传</title>
  </head>
  
  <body>
          <s:form action="upload" enctype="multipart/form-data" method="post">
              <s:textfield name="title" label="标题"/>
              <s:file name="upload" label="选择文件"/>
              <s:submit name="submit" value="文件上传"/>
          
          </s:form>
  </body>
</html>

2)开发实现文件上传的Action

package cn.happy.action;


import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport implements Action{
        //封装上传文件属性
        private String upload;
        //封装上传文件的类型
        private String uploadContentType;
        //封装上传文件的名称
        private String uploadFileName;
        //获取文件上传路径
        private String savePath;
        
        @Override
        public String execute() throws Exception{
            byte[] buffer=new byte[1024];
            //读取文件
            FileInputStream fis=new FileInputStream(getUpload());
            //保存文件,并设置保存目录的路径
            FileOutputStream fos=new FileOutputStream(getSavePath()+"\"+this.getUploadFileName());
            int length=fis.read(buffer);
            while(length>0){
                //每次写入长度的内容
                fos.write(buffer,0,length);
                length=fis.read(buffer);
            }
            fis.close();
            fos.flush();
            fos.close();
            return SUCCESS;
            
        }
        //获取上传文件的保存路径
        //通过读取存放目录获取的保存路径
        public String getSavePath() {
            return ServletActionContext.getServletContext().getRealPath(savePath);
        }
        public void setSavePath(String savePath) {
            this.savePath = savePath;
        }
        public String getUpload() {
            return upload;
        }
        public void setUpload(String upload) {
            this.upload = upload;
        }
        public String getUploadContentType() {
            return uploadContentType;
        }
        public void setUploadContentType(String uploadContentType) {
            this.uploadContentType = uploadContentType;
        }
        public String getUploadFileName() {
            return uploadFileName;
        }
        public void setUploadFileName(String uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
        
    
        
        
    
}

3)Struts.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 >
    <!--  <constant name="struts.devMode" value="true" /> -->
     <constant name="struts.devMode" value="false" />  
    <!--创建一个default包,继承自Struts2的struts-default包  -->
    <package name="default" namespace="" extends="struts-default">
    <action name="upload" class="cn.happy.action.UploadAction">
        <!-- 通过param参数设置保存目录路径 -->
        <param name="savePath">/upload</param>
        <result name="success">upload_success.jsp</result>
        </action>
</package>  

</struts>

4)在成功页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>文件上传成功</title>
    
    

  </head>
  
  <body>
  您所上传的文件是:<s:property value="uploadFileName"/>
 文件类型:<s:property value="uploadContentType"/>
 文件路径:<s:property value="savePath"/>
  </body>
</html>

三、实现文件下载

1)下载页面准备

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>文件下载</title>

  </head>
  
  <body>
    <a href="download?fileName=007.jpg">点击此处下载文档</a>
  </body>
</html>

2)开始实现文件下载的Action

package cn.happy.action;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;



import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;



@SuppressWarnings("serial")
public class FileDownAction  extends ActionSupport {

        //读取下载的文件目录
    private String inputPath;
    //下载文件的文件名
    private String fileName;
    //读取下载文件的输入流
   
    @SuppressWarnings("unused")
    private InputStream inputStream;
    
    //下载的文件类型
    private String conetntType;
    //创建inputStream输入流
    

    @Override
    public String execute() throws Exception {
        
        return SUCCESS;
    }
    
    


    public InputStream getInputStream() throws FileNotFoundException {
        String path=ServletActionContext.getServletContext().getRealPath(inputPath);
        return new BufferedInputStream(new FileInputStream(path+"\"+fileName));
    }




    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }




    public String getInputPath() {
        return inputPath;
    }
    public void setInputPath(String inputPath) {
        this.inputPath = inputPath;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public String getConetntType() {
        return conetntType;
    }
    public void setConetntType(String conetntType) {
        this.conetntType = conetntType;
    }
    

    
}

3)Struts.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 >
    <!--  <constant name="struts.devMode" value="true" /> -->
     <constant name="struts.devMode" value="false" />  
    <!--创建一个default包,继承自Struts2的struts-default包  -->
    <package name="default" namespace="" extends="struts-default">
    <action name="upload" class="cn.happy.action.UploadAction">
      
        <!-- 文件下载 -->
        <action name="download" class="cn.happy.action.FileDownAction">
            <param name="inputPath">/upload</param>
            <result name="success" type="stream">
                <param name="conetntType">application/octet-stream</param>
                <!-- <param name="conetntType">image/gif</param> -->
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">attachement;filename="${fileName}"</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>
        
    </package>

        
    
    

</struts>

注意!!!!

                        contentType对应的文件类型

        文件类型                                                           contentType设置                                        
  Word     application/msword
  Execl     Application/vnd.ms-excel
  PPT     Application/vnd.ms-powerpoint
  图片     image/gif、image/bmp、image/jpeg
  文本文件     text/plain
  HTML网页     text/html
  可执行文件     application/octet-stream
原文地址:https://www.cnblogs.com/yejiaojiao/p/5846281.html