关闭 x
IT技术网
    技 采 号
    ITJS.cn - 技术改变世界
    • 实用工具
    • 菜鸟教程
    IT采购网 中国存储网 科技号 CIO智库

    IT技术网

    IT采购网
    • 首页
    • 行业资讯
    • 系统运维
      • 操作系统
        • Windows
        • Linux
        • Mac OS
      • 数据库
        • MySQL
        • Oracle
        • SQL Server
      • 网站建设
    • 人工智能
    • 半导体芯片
    • 笔记本电脑
    • 智能手机
    • 智能汽车
    • 编程语言
    IT技术网 - ITJS.CN
    首页 » JAVA »Java Struts文件上传和下载详解

    Java Struts文件上传和下载详解

    2015-03-31 00:00:00 出处:四火的唠叨
    分享

    Struts2文件上传

    Struts 2框架提供了内置支持处理文件上传使用基于HTML表单的文件上传。上传一个文件时,它通常会被存储在一个临时目录中,他们应该由Action类进行处理或移动到一个永久的目录,以确保数据不丢失。

    请注意,服务器有一个安全策略可能会禁止写到目录以外的临时目录和属于web应用的目录。

    在Struts中的文件上传是通过预先定义的拦截文件上传拦截器这是可通过org.apache.struts2.interceptor.FileUploadInterceptor类的defaultStack中的一部分。仍然可以使用在struts.xml中设置各种参数,我们将在下面看到。

    视图文件index.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <%
    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="Upload.action" method="post" enctype="multipart/form-data">
          <label for="myFile">你要上传的文件</label>
          <input type="file" name="myFile" /><br>
    
          <input type="submit" value="上传"/>
       </form>
      </body>
    </html>

    在上面的例子中值得注意几点说明。首先,表单的enctype属性设置为multipart/ form-data。这应该是设置为使得处理文件上传文件上传。下一个点值得注意的是表单的 action方法上传和文件上传字段的名称 – myFile。我们需要这些信息创建操作方法和struts配置。

    接下来让我们创建一个简单的 jsp 文件的success.jsp 结果显示我们的文件上传的情况下成功。

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>文件上传</title>
    </head>
    <body>
    成功
    </body>
    </html>

    创建action类: 处理上传文件

    package com.oumyye.FileUpload;
    
    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class FileUploadAction extends ActionSupport{
            private File myFile;
           private String myFileContentType;
           private String myFileFileName;
           private String destPath;
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        @Override
        public String execute() throws Exception {
            // TODO Auto-generated method stub
             destPath = "e:/upload/"; 
              try{
                  System.out.println("Src File name: " + myFile);  
                  System.out.println("我的文件名"+myFileFileName);
                  System.out.println("我的文件类型"+ myFileContentType);
                  File destFile  = new File(destPath, myFileFileName);
                 FileUtils.copyFile(myFile, destFile);
              }catch(IOException e){
                 e.printStackTrace();
                 return ERROR;
              }
            return SUCCESS;
        }
        public File getMyFile() {
            return myFile;
        }
        public void setMyFile(File myFile) {
            this.myFile = myFile;
        }
        public String getMyFileContentType() {
            return myFileContentType;
        }
        public void setMyFileContentType(String myFileContentType) {
            this.myFileContentType = myFileContentType;
        }
        public String getMyFileFileName() {
            return myFileFileName;
        }
        public void setMyFileFileName(String myFileFileName) {
            this.myFileFileName = myFileFileName;
        }
        public String getDestPath() {
            return destPath;
        }
        public void setDestPath(String destPath) {
            this.destPath = destPath;
        }
        public static long getSerialversionuid() {
            return serialVersionUID;
        }
    }

    配置文件:

    可以使用恒定的标签在应用程序 struts.xml文件,像我一样改变要上传的文件的最大大小。让我们有我们的在struts.xml如下:

    < xml version="1.0" encoding="UTF-8"  >
    <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
    <struts>
        <constant name="struts.devMode" value="false" />
        <!-- 指定每次请求到达,重新加载资源文件 -->
        <constant name="struts.i18n.reload" value="true" />
        <!-- 指定每次配置文件更改后,自动重新加载 -->
        <constant name="struts.configuration.xml.reload" value="true" />
        <!-- 把主题配置为simple -->
        <constant name="struts.ui.theme" value="simple" />
    
        <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
        <constant name="struts.multipart.maxSize" value="10701096" />
    <!--文件上传-->
        <package name="upload" namespace="/" extends="struts-default">
            <action name="Upload" class="com.oumyye.FileUpload.FileUploadAction">
                <result name="success">/success.jsp</result>
                <result name="input">/index.jsp</result>
            </action>
    
    <!--文件下载-->
             <action name="FileDownload" class="com.oumyye.action.FileDownload">  
               <result name="success" type="stream">  
                   <param name="contentType">text/plain</param>  
                   <param name="contentDisposition">attachment;fileName="${fileName}"</param>  
                   <param name="inputName">downloadFile</param>  
                   <param name="bufferSize">1024</param>  
               </result>  
           </action>  
        </package>
    </struts>

    以下是web.xml文件中的内容,与Struts2的基本配置一样

    < xml version="1.0" encoding="UTF-8" >
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
      <display-name>Struts2_1000_FileUpload</display-name>
      <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>*.action</url-pattern>
      </filter-mapping>
    </web-app>

    上述代码即可完成文件上传

    文件下载

    视图文件filedownload.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">    
        <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>
        <h2>文件下载内容:</h2><br/>
        Dream.jpg:<a href="FileDownload.action">点击下载</a><br/>
      </body>
    </html>

    创建action类: 处理上传文件,

    package com.oumyye.action;
    import java.io.InputStream;
    import org.apache.struts2.ServletActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    //文件下载
    public class FileDownload extends ActionSupport{
        private String fileName;
        public String getFileName() {
            return fileName;
        }
    
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
        //返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流
        public InputStream getDownloadFile() throws Exception
        {
    
               this.fileName = "hello.jpg" ;
               //获取资源路径
               return ServletActionContext.getServletContext().getResourceAsStream("upload/"+this.fileName) ;
            }
        @Override
        public String execute() throws Exception {   
            return SUCCESS;
        }
    
    }

    配置文件同上

    下载时可能会出现错误

    Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action.

    可能的原因:

    1.文件路径不对,根本就没有取到文件。这种情况下,可以将获得InputStream的那条语句放在system.out.println()中输出一下,若为null,那就是路径不对了,或者说得准确些就根本没有找到文件。

    2.在action中没有写配置文件中”<param name=”inputName”>”后面属性的那个get方法.

    上一篇返回首页 下一篇

    声明: 此文观点不代表本站立场;转载务必保留本文链接;版权疑问请联系我们。

    别人在看

    正版 Windows 11产品密钥怎么查找/查看?

    还有3个月,微软将停止 Windows 10 的更新

    Windows 10 终止支持后,企业为何要立即升级?

    Windows 10 将于 2025年10 月终止技术支持,建议迁移到 Windows 11

    Windows 12 发布推迟,微软正全力筹备Windows 11 25H2更新

    Linux 退出 mail的命令是什么

    Linux 提醒 No space left on device,但我的空间看起来还有不少空余呢

    hiberfil.sys文件可以删除吗?了解该文件并手把手教你删除C盘的hiberfil.sys文件

    Window 10和 Windows 11哪个好?答案是:看你自己的需求

    盗版软件成公司里的“隐形炸弹”?老板们的“法务噩梦” 有救了!

    IT头条

    公安部:我国在售汽车搭载的“智驾”系统都不具备“自动驾驶”功能

    02:03

    液冷服务器概念股走强,博汇、润泽等液冷概念股票大涨

    01:17

    亚太地区的 AI 驱动型医疗保健:2025 年及以后的下一步是什么?

    16:30

    智能手机市场风云:iPhone领跑销量榜,华为缺席引争议

    15:43

    大数据算法和“老师傅”经验叠加 智慧化收储粮食尽显“科技范”

    15:17

    技术热点

    商业智能成CIO优先关注点 技术落地方显成效(1)

    用linux安装MySQL时产生问题破解

    JAVA中关于Map的九大问题

    windows 7旗舰版无法使用远程登录如何开启telnet服务

    Android View 事件分发机制详解

    MySQL用户变量的用法

      友情链接:
    • IT采购网
    • 科技号
    • 中国存储网
    • 存储网
    • 半导体联盟
    • 医疗软件网
    • 软件中国
    • ITbrand
    • 采购中国
    • CIO智库
    • 考研题库
    • 法务网
    • AI工具网
    • 电子芯片网
    • 安全库
    • 隐私保护
    • 版权申明
    • 联系我们
    IT技术网 版权所有 © 2020-2025,京ICP备14047533号-20,Power by OK设计网

    在上方输入关键词后,回车键 开始搜索。Esc键 取消该搜索窗口。