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方法.

Java Struts文件上传和下载详解的更多相关文章

  1. express文件上传中间件Multer详解

    express文件上传中间件Multer详解 转载自:https://www.cnblogs.com/chengdabelief/p/6580874.html   Express默认并不处理HTTP请 ...

  2. java的文件上传和下载 抄袭别人的.在底部有说明.

    =======后续 这里采用的是输出流的方式,我电脑装的是windows系统,测试没有问题,但是当把项目放到Linux系统上跑时,就会出现保存位置错误的情况, 指定的路径就会被当做文件名的一部分保存了 ...

  3. Java 实现文件上传、下载、打包、文件copy、文件夹copy。

    文件and文件夹copy package org.test; import java.io.*; public class FileCopy { /** * 复制单个文件 * * @param old ...

  4. struts文件上传和下载

    文件上传 jsp中 <a href="/file/new.action">文件上传案例</a> fileaction中 @Override public S ...

  5. SpringMVC+BUI实现文件上传(附详解,源码下载)

    中午有限时间写这博文,前言就不必多说了,直奔主题吧. BUI是一个前端框架,关于BUI的介绍请看博主的文章那些年用过的一些前端框架. 下面我们开始实例的讲解! 一.效果演示: 上传成功后,会发现本地相 ...

  6. JAVA SFTP文件上传、下载及批量下载

    JavaJsch  1.jsch官方API查看地址(附件为需要的jar) http://www.jcraft.com/jsch/ 2.jsch简介 JSch(Java Secure Channel)是 ...

  7. java+超大文件上传与下载

    ​这里先说下spring mvc 遇到的坑,就是如果文件上传时,后端这样写public String file1(HttpServletRequest request),根据request拿到的东西是 ...

  8. 文件上传插件uploadify详解

    官网:http://www.uploadify.com/ 基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件. 要求使用jquery1.4或以上 ...

  9. Input标签文件上传,使用详解

    1.html添加标签按钮 <button ion-button (click)="selectVideo()">添加</button> <input ...

随机推荐

  1. angularjs hover

    <ul class="pdl-15"><li ng-repeat="order in vm.selectOrders" ng-class=&q ...

  2. oracle模糊查询效率可这样提高

    1.使用两边加'%'号的查询,oracle是不通过索引的,所以查询效率很低. 例如:select count(*) from lui_user_base t where t.user_name lik ...

  3. base64加密解密文件

    1 //字符串加密 -(void)demo1 { //普通的 8 bit二进制数据 NSString *str = @"hello world!"; //将字符串转换成二进制数据 ...

  4. hdoj 2040

    #include<stdio.h>int i,j,s1,s2;int cha(int a,int b){ s1=0; s2=0;   for(i=1;i<a;i++)   {    ...

  5. TIFF6 Packbit algorithm

    “Packbits” from ISO 12369 参考TIFF 6.0 Specification,点击TIFF, Version 6.0: @Section 9: PackBits Compres ...

  6. java中jdk环境配置

    配置java环境,俗称jdk环境 首先进入配置环境的目录下:右键鼠标我的电脑->属性->高级系统设置->环境变量,在对应的"系统变量"框下配置一下变量: 规范的配 ...

  7. grep操作

    这个程序的名称来自Unix文本编辑器ed类似操作的命令: g/re/p 这个命令搜索整个文件中匹配给定正则表达式的文本行,并显示出来.有很多不同的命令行用于改变grep的默认行为,包括显示出不匹配的文 ...

  8. Oracle数据库之rownum

    1. 介绍 当我们在做查询时,经常会遇到如查询限定行数或分页查询的需求,MySQL中可以使用LIMIT子句完成,在MSSQL中可以使用TOP子句完成,那么在Oracle中,我们如何实现呢? Oracl ...

  9. Sql Server 时间格式

    问题引出: Sql Server 里 dateTime 数据类型,会精确到毫秒.如果我们 在插入一条数据的时候,使用 GetDate() 记录 这个记录插入的时间,则会插入当前时间,精确到毫秒.在查询 ...

  10. 为什么Android AsyncTask的使用要遵循五大原则

    引言 AsyncTask是一个围绕Handler和Thread而设计的助手类,封装了在工作线程中与UI交互的细节,只需要对应重写几个回调方法即可,并使得代码更加简洁,优雅.但要注意的是AsyncTas ...