Struts2.0实现的文件上传(单附件和多附件)以及附件下载功能

本文介绍如何使用Struts2框架实现文件的上传和下载功能,包括单文件和多文件上传的过程及代码实现,并展示了如何配置Struts2拦截器以支持文件上传。
     --------------------------------------------------单附件上传:----------------------------------------------------------------

 

Action类:

package com.yourcompany.struts.uponloadfile;
import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.Date;

 import org.apache.struts2.ServletActionContext;

 import com.opensymphony.xwork2.ActionSupport;

 public class FileUploadAction extends ActionSupport  {
     private static final long serialVersionUID = 572146812454l ;
     private static final int BUFFER_SIZE = 16 * 1024 ;
   
     private File myFile;
     private String contentType;
     private String fileName;
     private String imageFileName;
     private String caption;
   
     public void setMyFileContentType(String contentType)  {
         this .contentType = contentType;
    }
     //还有myFileContentType(上传文件的MIME类型)和myFileFileName(上传文件的文件名,该文件名不包括文件的路径)。因此,<s:file name="xxx" />
     //对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。
     public void setMyFileFileName(String fileName)  {
         this .fileName = fileName;
    }
       
     public void setMyFile(File myFile)  {
         this .myFile = myFile;
    }
   
     public String getImageFileName()  {
         return imageFileName;
    }
   
     public String getCaption()  {
         return caption;
    }
 
      public void setCaption(String caption)  {
         this .caption = caption;
    }
   
     private static void copy(File src, File dst)  {
         try  {
            InputStream in = null ;
            OutputStream out = null ;
             try  {   
              //输入到缓冲流
                in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
                out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
                 byte [] buffer = new byte [BUFFER_SIZE];
                 while (in.read(buffer) > 0 )  {
                    out.write(buffer);
                }
             } finally  {
                 if ( null != in)  {
                    in.close();
                }
                  if ( null != out)  {
                    out.close();
                }
            }
         } catch (Exception e)  {
            e.printStackTrace();
        }
    }
   
     private static String getExtention(String fileName)  {
         int pos = fileName.lastIndexOf( "." );
         return fileName.substring(pos+1);//获得后缀名
    }
 
    @Override
     public String execute()      {       
        imageFileName = new Date().getTime() + getExtention(fileName);//合成图片的名称
        System.out.println("================="+imageFileName+"========="+ServletActionContext.getServletContext().getRealPath("WebRoot/UploadImages" ));
        File imageFile = new File(ServletActionContext.getServletContext().getRealPath( "/UploadImages") + "/" +imageFileName);
        copy(myFile, imageFile);
         return SUCCESS;
    }
}

 

struts.xml配置:

 

 

 

<action name ="fileUpload" class ="com.yourcompany.struts.uponloadfile.FileUploadAction" >
           
              <interceptor-ref name ="fileUpload" >
                <param name ="allowedTypes" >
                   image/bmp,image/png,image/gif,image/jpeg
                </param >
            </interceptor-ref > 
            <!-- <interceptor-ref name="timer"/>  用于测试action的执行时间 -->
         
            <interceptor-ref name ="defaultStack" />   
            <result name="input">/uploadfile_index.jsp</result >
            <result name="success">/uploadfile_result.jsp </result >
        </action >

 

 

 

 

uploadfile_index.jsp:

jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ taglib uri="/struts-tags" prefix="s" %>


<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
      
    <title>uploadfile_index.jsp</title> 
      
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="exires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="This is my page"> 
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    --> 
 
  </head> 
    
  <body> 
    选择上传文件:类型是图片
  <s:fielderror />
    <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >
        <s:file name ="myFile"   label ="Image File" />
        <s:textfield name ="caption" label ="Caption" />       
        <s:submit />
    </s:form >
 
  </body> 
</html> 

 

uploadfile_result.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ taglib uri="/struts-tags" prefix="s" %>


<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
      
    <title>uploadfile_result.jsp</title> 
      
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="This is my page"> 
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    --> 
 
  </head> 
    
  <body> 
  <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >
        <img src ='UploadImages/<s:property value ="imageFileName" /> ' />
        <br />
        <s:property value ="caption" />
    </div >


  </body> 
</html> 

 

--------------------------------------------------多附件上传:----------------------------------------------------------------

 

Action类:

package com.yourcompany.struts.uponloadfile;
import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.OutputStream;
import java.util.ArrayList;
 import java.util.Date;
import java.util.List;

 import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

 public class maxFileUploadAction extends ActionSupport  {
     private static final long serialVersionUID = 572146812454l ;
     private static final int BUFFER_SIZE = 16 * 1024 ;
   
     private File[] uploads;
     private String[] uploadFileNames;
     private String[] uploadContentTypes;

     public File[] getUpload()  { return this .uploads; }
      public void setUpload(File[] uploads)  { this .uploads = uploads; }
 
      public String[] getUploadFileName()  { return this .uploadFileNames; }
      public void setUploadFileName(String[] uploadFileName)  { this .uploadFileNames = uploadFileName; }
 
      public String[] getUploadContentType()  { return this .uploadContentTypes; }
      public void setUploadContentType(String[] uploadContentType)  { this .uploadContentTypes = uploadContentType;
      }
     private static void copy(File src, File dst)  {
         try  {
            InputStream in = null ;
            OutputStream out = null ;
             try  {   
              //输入到缓冲流
                in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
                out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
                 byte [] buffer = new byte [BUFFER_SIZE];
                 while (in.read(buffer) > 0 )  {
                    out.write(buffer);
                }
             } finally  {
                 if ( null != in)  {
                    in.close();
                }
                  if ( null != out)  {
                    out.close();
                }
            }
         } catch (Exception e)  {
            e.printStackTrace();
        }
    }
   
     private static String getExtention(String fileName)  {
         int pos = fileName.lastIndexOf( "." );
         return fileName.substring(pos+1);//获得后缀名
    }
 
    @Override
     public String execute(){    
     for(int i=0;i<3;i++){
       String imageFileName = new Date().getTime() +getExtention(uploadFileNames[i]);//合成图片的名称
        System.out.println("================="+imageFileName+"========="+ServletActionContext.getServletContext().getRealPath("WebRoot/UploadImages" ));
        File imageFile = new File(ServletActionContext.getServletContext().getRealPath( "/UploadImages") + "/" +imageFileName);
        copy(uploads[i], imageFile);
     }    
         return SUCCESS;
    }
}

 

 

 

struts.xml配置:

 

<action name ="maxfileUpload" class ="com.yourcompany.struts.uponloadfile.maxFileUploadAction" >
 <interceptor-ref name ="fileUpload" />
 <!--  <interceptor-ref name ="fileUploadStack" />  -->
  <interceptor-ref name ="defaultStack" />
 <result name="success">/uploadfile_maxresult.jsp </result >   
        </action >

 

jsp:

uploadfile_maxindex.jsp:

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ taglib uri="/struts-tags" prefix="s" %>


<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
      
    <title>uploadfile_maxindex.jsp</title> 
      
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="exires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="This is my page"> 
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    --> 
 
  </head> 
    
  <body> 
  选择上传文件:不限类型
  <s:form action ="maxfileUpload" method ="POST" enctype ="multipart/form-data" >
    <s:file label ="File (1)" name ="upload" />
    <s:file label ="File (2)" name ="upload" />
    <s:file label ="File (3)" name ="upload" />
    <s:submit />
</s:form >
 
  </body> 
</html> 

 

 

uploadfile_maxresult.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ taglib uri="/struts-tags" prefix="s" %>


<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
      
    <title>uploadfile_maxresult.jsp</title> 
      
    <meta http-equiv="pragma" content="no-cache"> 
    <meta http-equiv="cache-control" content="no-cache"> 
    <meta http-equiv="exires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
    <meta http-equiv="description" content="This is my page"> 
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    --> 
 
  </head> 
    
  <body> 
 <h4>上传成功</h4>
 
  </body> 
</html> 

 

 

 

 

 

 

 

 

 

--------------------------------------------------附件下载:----------------------------------------------------------------

 

Action类:

 

package com.yourcompany.struts.filedown;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;

public class Filedown implements Action {

private String fileName;// 初始的通过param指定的文件名属性

private String inputPath;// 指定要被下载的文件路径


public InputStream getInputStream() throws Exception {

// 通过 ServletContext,也就是application 来读取数据

return ServletActionContext.getServletContext().getResourceAsStream(inputPath);

}

public String execute() throws Exception {

return SUCCESS;

}

public void setInputPath(String value) {

inputPath = value;

}

public void setFileName(String fileName) {

this.fileName = fileName;

}

/** 提供转换编码后的供下载用的文件名 */

public String getDownloadFileName() {

String downFileName = fileName;

try {

downFileName = new String(downFileName.getBytes(), "ISO8859-1");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return downFileName;

}

}

 

struts.xml配置:

 

 


<!-- 下载现有文件 -->
<action name="download3" class="com.yourcompany.struts.filedown.Filedown">
<param name="inputPath">/download/系统说明.doc</param>
<!-- 初始文件名 -->
<!-- 可以载页面传入 -->
<!-- <param name="fileName">系统说明.doc</param> -->
<result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<param name="inputName">inputStream</param>
<!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性
对应action类中的方法 getDownloadFileName() -->
<param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>

 

JSP:

 

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>filedown.jsp</title>
  
</head>
<body>   

<a href=" <s:url value="download3.action"> <s:param name="fileName">系统说明.doc</s:param> </s:url>">download</a>

</body>
</html>

【SCI复现】含可再生能源与储能的区域微电网最优运行:应对不确定性的解鲁棒性与非预见性研究(Matlab代码实现)内容概要:本文围绕含可再生能源与储能的区域微电网最优运行展开研究,重点探讨应对不确定性的解鲁棒性与非预见性策略,通过Matlab代码实现SCI论文复现。研究涵盖多阶段鲁棒调度模型、机会约束规划、需求响应机制及储能系统优化配置,结合风电、光伏等可再生能源出力的不确定性建模,提出兼顾系统经济性与鲁棒性的优化运行方案。文中详细展示了模型构建、算法设计(如C&CG算法、大M法)及仿真验证全过程,适用于微电网能量管理、电力系统优化调度等领域的科研与工程实践。; 适合人群:具备一定电力系统、优化理论Matlab编程基础的研究生、科研人员及从事微电网、能源管理相关工作的工程技术人员。; 使用场景及目标:①复现SCI级微电网鲁棒优化研究成果,掌握应对风光负荷不确定性的建模与求解方法;②深入理解两阶段鲁棒优化、分布鲁棒优化、机会约束规划等先进优化方法在能源系统中的实际应用;③为撰写高水平学术论文或开展相关课题研究提供代码参考技术支持。; 阅读建议:建议读者结合文档提供的Matlab代码逐模块学习,重点关注不确定性建模、鲁棒优化模型构建与求解流程,并尝试在不同场景下调试与扩展代码,以深化对微电网优化运行机制的理解。
个人防护装备实例分割数据集 一、基础信息 数据集名称:个人防护装备实例分割数据集 图片数量: 训练集:4,524张图片 分类类别: - Gloves(手套):工作人员佩戴的手部防护装备。 - Helmet(安全帽):头部防护装备。 - No-Gloves(未戴手套):未佩戴手部防护的状态。 - No-Helmet(未戴安全帽):未佩戴头部防护的状态。 - No-Shoes(未穿安全鞋):未佩戴足部防护的状态。 - No-Vest(未穿安全背心):未佩戴身体防护的状态。 - Shoes(安全鞋):足部防护装备。 - Vest(安全背心):身体防护装备。 标注格式:YOLO格式,包含实例分割的多边形坐标类别标签,适用于实例分割任务。 数据格式:来源于实际场景图像,适用于计算机视觉模型训练。 二、适用场景 工作场所安全监控系统开发:数据集支持实例分割任务,帮助构建能够自动识别工作人员个人防护装备穿戴状态的AI模型,提升工作环境安全性。 建筑与工业安全检查:集成至监控系统,实时检测PPE穿戴情况,预防安全事故,确保合规性。 学术研究与创新:支持计算机视觉在职业安全领域的应用研究,促进AI与安全工程的结合。 培训与教育:可用于安全培训课程,演示PPE识别技术,增强员工安全意识。 三、数据集优势 精准标注与多样性:每个实例均用多边形精确标注,确保分割边界准确;覆盖多种PPE物品及未穿戴状态,增加模型鲁棒性。 场景丰富:数据来源于多样环境,提升模型在不同场景下的泛化能力。 任务适配性强:标注兼容主流深度学习框架(如YOLO),可直接用于实例分割模型开发,支持目标检测分割任务。 实用价值高:专注于工作场所安全,为自动化的PPE检测提供可靠数据支撑,有助于减少工伤事故。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值