Struts2.0实现的文件上传(单附件和多附件)以及附件下载功能
--------------------------------------------------单附件上传:----------------------------------------------------------------
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>
Struts2.0实现的文件上传(单附件和多附件)以及附件下载功能相关推荐
- 学习日志day41(2021-09-03)(1、文件的上传 2、文件的查看 3、文件的下载 4、使用工具类上传文件 5、基于servlet3.0以上的文件上传 )
学习内容:学习JavaWeb(Day41) 1.文件的上传 2.文件的查看 3.文件的下载 4.使用工具类上传文件 5.基于servlet3.0以上的文件上传 1.文件的上传 (1)实现文件的上传需要 ...
- php104.tmp,ThinkPHP5.0多个文件上传后找不到临时文件的修改方法
这是修改之前的代码 if(!empty($_FILES)){ if(!empty($_FILES[org_positive])){ $org_positive = request()->file ...
- Struts2之文件上传(单文件/多文件)
<一>简述: Struts2的文件上传其实也是通过拦截器来实现的,只是该拦截器定义为默认拦截器了,所以不用自己去手工配置,<interceptor name="fileUp ...
- java struts2上传文件_java Struts2框架下实现文件上传功能
本文实例为大家分享了struts2框架实现文件上传的方法,供大家参考,具体内容如下 struts2的配置过程 (1)在项目中加入jar包 (2)web.xml中filter(过滤器)的配置 xmlns ...
- struts2的多个文件上传思路,小例子 ,仅供参考
2019独角兽企业重金招聘Python工程师标准>>> jsp页面的部分代码 <form action="insertcp.action" method=& ...
- 用VSCode开发一个asp.net core2.0+angular5项目(5): Angular5+asp.net core 2.0 web api文件上传...
第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 第三 ...
- 走进Struts2(六)— 文件上传和下载
一.文件上传 实现文件上传的方式有很多种,比如Apache的Common-FileUpload,但是实现起来非常的繁琐,而Struts2来实现文件上传则简单的多,默认也是基于Common-FileUp ...
- struts2和springmvc实现文件上传
struts2 struts有专门的文件上传功能,struts的Action已经脱离了servlet容器的范围,所以servlet中的smartupload不是很方便使用,甚至初始化servletCl ...
- struts2解决动态多文件上传的问题(上传文件与数据库字段一一对应)(转)
struts2多文件上传我想只要会用struts2的朋友都不会陌生,但是怎么在action中根据用户上传的文 件把文件路径写到数据库中对应的字段上呢?ps:我的意思是这样,页面上有固定的5个上传文件的 ...
最新文章
- SSM开发 | 配合Mybatis,通过泛型实现 BaseService ,抽象增改删查方法
- php 安全mysql,关于php:我从mysql注入安全吗?
- linux vps 运行exe文件夹,linux 64位下安装wine1.6 Windows模拟器(用来运行.exe文件) 编译安装32位wine...
- 桶排序/Bucket Sort
- [转]ORA-01555错误总结(二)
- siri不能识别语音
- APT攻防整理-常用CVE
- 提高IT团队工作效率的建议
- 经济学人精读丨中国的电子商务
- 随着数字化转型加速,Entrust Datacard更名为“Entrust”
- 工具nmap常用命令总结
- 前沿分享|数澜科技联合创始人副总裁 江敏:基于云原生数据仓库AnalyticDB PostgreSQL的最佳实践
- 关于程序员做副业这事
- Java毕设项目房产中介管理系统(java+VUE+Mybatis+Maven+Mysql)
- 计算机农业类的sci,农林类容易录用的sci期刊有哪些?
- SHT11的C语言,用SHT11 构成的温湿度监测系统
- 九龙证券|本周5只新股申购,特斯拉、蔚来、理想的供应商来A股了!
- 正则表达式30分钟入门教程
- windows系统本地批量预览svg图标
- ebtables配置IPMAC绑定关系