struts2的上传和下载

来源:互联网 发布:day one windows 编辑:程序博客网 时间:2024/04/29 14:38
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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>My JSP 'index.jsp' starting page</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>  <form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">  用户名:<input type="text" name="userName"><br/>  文件:<input type="file" name="headImg"><br/>    <input type="submit" value="上传">  </form>  </body></html>

上传下载的struts2配置文件,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_" extends="struts-default"><!-- 注意: action 的名称不能用关键字"fileUpload" --><action name="fileUploadAction" class="cn.itcast.e_fileupload.FileUpload"><!-- 限制运行上传的文件的类型 --><interceptor-ref name="defaultStack"><!-- 限制运行的文件的扩展名 --><param name="fileUpload.allowedExtensions">txt,jpg,jar</param><!-- 限制运行的类型   【与上面同时使用,取交集】<param name="fileUpload.allowedTypes">text/plain</param>--></interceptor-ref><result name="success">/e/success.jsp</result><!-- 配置错误视图 --><result name="input">/e/error.jsp</result></action><action name="down_*" class="cn.itcast.e_fileupload.DownAction" method="{1}"><!-- 列表展示 --><result name="list">/e/list.jsp</result><!-- 下载操作 --><result name="download" type="stream"><!-- 运行下载的文件的类型:指定为所有的二进制文件类型 -->   <param name="contentType">application/octet-stream</param>      <!-- 对应的是Action中属性: 返回流的属性【其实就是getAttrInputStream()】 -->   <param name="inputName">attrInputStream</param>      <!-- 下载头,包括:浏览器显示的文件名 -->   <param name="contentDisposition">attachment;filename=${downFileName}</param>  <!-- 缓冲区大小设置 -->   <param name="bufferSize">1024</param></result></action></package></struts>

FileUpload.java

public class Fileupload extends ActionSupport{private File headImg;private String headImgContentType;private String headImgFileName;@Override      public String execute() throws Exception {   /******拿到上传的文件,进行处理******/   if (headImg!=null) {String filePath = ServletActionContext.getServletContext().getRealPath("upload/user");String fileName = UUID.randomUUID().toString().replace("-", "")+headImgFileName.substring(headImgFileName.lastIndexOf(".")); FileUtils.copyFile(headImg,  new File(filePath,fileName));}public File getHeadImg() {return headImg;}public void setHeadImg(File headImg) {this.headImg = headImg;}public String getHeadImgContentType() {return headImgContentType;}public void setHeadImgContentType(String headImgContentType) {this.headImgContentType = headImgContentType;}public String getHeadImgFileName() {return headImgFileName;}public void setHeadImgFileName(String headImgFileName) {this.headImgFileName = headImgFileName;}}


List.jsp
List.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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>下载列表</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">      </head>    <body>  <table border="1" align="center">  <tr>  <td>编号</td>  <td>文件名</td>  <td>操作</td>  </tr>  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  <c:forEach var="fileName" items="${fileNames}" varStatus="vs">  <tr>  <td>${vs.count }</td>  <td>${fileName }</td>  <td>  <!-- 构建一个url -->  <c:url var="url" value="down_down">  <c:param name="fileName" value="${fileName}"></c:param>  </c:url>    <a href="${url }">下载</a>  </td>  </tr>  </c:forEach>  </table>  </body></html>

DownAction.java

public class DownAction extends ActionSupport {/*************1. 显示所有要下载文件的列表*********************/public String list() throws Exception {//得到upload目录路径String path = ServletActionContext.getServletContext().getRealPath("/upload");// 目录对象File file  = new File(path);// 得到所有要下载的文件的文件名String[] fileNames =  file.list();// 保存ActionContext ac = ActionContext.getContext();// 得到代表request的map (第二种方式)Map<String,Object> request= (Map<String, Object>) ac.get("request");request.put("fileNames", fileNames);return "list";}/*************2. 文件下载*********************/// 1. 获取要下载的文件的文件名private String fileName;public void setFileName(String fileName) {// 处理传入的参数中问题(get提交)try {fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}// 把处理好的文件名,赋值this.fileName = fileName;}//2. 下载提交的业务方法 (在struts.xml中配置返回stream)public String down() throws Exception {return "download";}// 3. 返回文件流的方法public InputStream getAttrInputStream(){return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);}// 4. 下载显示的文件名(浏览器显示的文件名)public String getDownFileName() {// 需要进行中文编码try {fileName = URLEncoder.encode(fileName, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}return fileName;}}



0 0