欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaWeb文件上传下载功能深入分析(二)

程序员文章站 2024-03-13 08:51:45
接着上一篇叙述: 二、文件上传与下载 struts2开发的三板斧,页面jsp—配置文件struts2.xml—-还有动作类action 文件上传前提: form表...

接着上一篇叙述:

二、文件上传与下载

struts2开发的三板斧,页面jsp—配置文件struts2.xml—-还有动作类action

文件上传前提:
form表单的method必须是post
form表单的enctype必须是multipart/form-data
提供type=”file”的上传输入域

struts 对文件上传的支持的一些规则

JavaWeb文件上传下载功能深入分析(二)

1、单文件上传

开发步骤:

1)、在web-inf/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载

2)、第二步:编写upfile.jsp ,把form表的enctype设置为:“multipart/form-data“,如下:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<body>
  <s:actionerror/>
  <hr/>
  <s:fielderror></s:fielderror>
  <form action="${pagecontext.request.contextpath}/upload1.action" method="post" enctype="multipart/form-data"><!-- 以mime的方式传递
-->
    用户名:<input type="text" name="username"/><br/>
    靓照:<input type="file" name="photo"/><br/>
    <input type="submit" value="上传"/>
  </form>
 </body>

编写错误页面error.jsp

 <body>
  服务器忙,一会再试。
 </body>

success.jsp

 <body>
  上传成功
 </body>

3)、编写uploadaction1 类:在action类中添加属性,属性对应于表单中文件字段的名称:

package com.itheima.actions;

import java.io.file;
import java.io.ioexception;

import org.apache.commons.io.fileutils;
import org.apache.struts2.servletactioncontext;

import com.opensymphony.xwork2.actionsupport;
//文件上传:fileupload拦截器完成的
public class uploadaction1 extends actionsupport {

  private string username;
  private file photo;//和表单的上传字段名保持一致。类型是file类型的
  private string photofilename;//上传的文件名
  private string photocontenttype;//上传文件的mime类型

  //省略getter和setter方法
  public string upload(){
    system.out.println(photofilename+":"+photocontenttype);
    //普通字段:
    system.out.println(username);
    //上传字段:上传到某个文件夹。存到应用的images目录下
    string realpath = servletactioncontext.getservletcontext().getrealpath("/images");
    file directory = new file(realpath);
    if(!directory.exists()){
      directory.mkdirs();
    }
    try {
      fileutils.copyfile(photo, new file(directory, photofilename));
      return success;
    } catch (ioexception e) {
      e.printstacktrace();
      return error;
    }

  }
}

在struts.xml文件中增加如下配置

<action name="upload1" class="com.itheima.actions.uploadaction1" method="upload">
  <interceptor-ref name="defaultstack">
    <param name="fileupload.allowedtypes">image/jpeg,image/png</param>
    <param name="fileupload.allowedextensionsset">jpg,jpeg,png</param>
  </interceptor-ref>
  <result>/success.jsp</result>
  <result name="error">/error.jsp</result>
  <result name="input">/index.jsp</result>
</action>

原理分析:

a 、fileupload 拦截器负责处理文件的上传操作, 它是默认的 defaultstack 拦截器栈的一员. 拦截器有 3 个属性可以设置.
 •maximumsize: 上传文件的最大长度(以字节为单位), 默认值为 2 mb
 •allowedtypes: 允许上传文件的类型, 各类型之间以逗号分隔
 •allowedextensions: 允许上传文件扩展名, 各扩展名之间以逗号分隔
可以在 struts.xml 文件中覆盖这 3 个属性 

JavaWeb文件上传下载功能深入分析(二)

b、超出大小或非法文件的上传,会报错(转向一个input的视图)

通过:
<s:actionerror/> <s:feilderror/>显示错误消息的提示

c、错误消息提示改为中文版:借助国际化的消息资源文件

如果是通过配置全局默认参数引起的错误,最好用全局的消息资源文件。
struts2默认的提示资源文件:struts2-core-**.jar 的org.apache.struts2的struts-message.properties文件中。比着key值覆盖对应的value即可。

配置如下:

struts.messages.error.uploading=error uploading: {0}
struts.messages.error.file.too.large=file too large: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=content-type not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=file extension not allowed: {0} "{1}" "{2}" {3}

{0}:<input type=“file” name=“uploadimage”>中name属性的值
{1}:上传文件的真实名称
{2}:上传文件保存到临时目录的名称
{3}:上传文件的类型(对struts.messages.error.file.too.large是上传文件的大小)

源码:

JavaWeb文件上传下载功能深入分析(二)

修改显示错误的资源文件的信息

第一步:创建新的资源文件 例如fileuploadmessage.properties,放置在src下
           在该资源文件中增加如下信息
struts.messages.error.uploading=上传错误: {0}
struts.messages.error.file.too.large=上传文件太大: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=上传文件的类型不允许: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=上传文件的后缀名不允许: {0} "{1}" "{2}" {3}

 第二步:在struts.xml文件加载该资源文件

       <!-- 配置上传文件的出错信息的资源文件 -->
       <constant name="struts.custom.i18n.resources" value=“cn….xxx.fileuploadmessage“/>

2、多文件上传

上传多个文件, 可以使用数组或 list,其他和单文件上传类似。

package com.itheima.actions;

import java.io.file;
import java.io.ioexception;

import org.apache.commons.io.fileutils;
import org.apache.struts2.servletactioncontext;

import com.opensymphony.xwork2.actionsupport;
//文件上传:fileupload拦截器完成的
public class uploadaction2 extends actionsupport {

  private string username;
  private file[] photo;//和表单的上传字段名保持一致。类型是file类型的 .数组或list
  private string[] photofilename;//上传的文件名
  private string[] photocontenttype;//上传文件的mime类型

  public string upload(){
    //上传字段:上传到某个文件夹。存到应用的images目录下
    string realpath = servletactioncontext.getservletcontext().getrealpath("/images");
    file directory = new file(realpath);
    if(!directory.exists()){
      directory.mkdirs();
    }
    try {
      for(int i=0;i<photo.length;i++){
        fileutils.copyfile(photo[i], new file(directory, photofilename[i]));
      }
      return success;
    } catch (ioexception e) {
      e.printstacktrace();
      return error;
    }

  }
}

3、文件下载

原理:struts2提供了stream结果类型,该结果类型就是专门用于支持文件下载功能的
指定stream结果类型 需要指定一个 inputname参数,该参数指定一个输入流,提供被下载文件的入口

编码步骤:
1)、动作类downloadaction :

package com.itheima.actions;

import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.inputstream;
import java.net.urlencoder;

import org.apache.commons.io.filenameutils;
import org.apache.struts2.servletactioncontext;

import com.opensymphony.xwork2.actionsupport;

public class downloadaction extends actionsupport {
  private inputstream image;//用in有问题的
  private string filename;//文件名
  private long filesize;
  public inputstream getimage() {
    return image;
  }

  public void setimage(inputstream image) {
    this.image = image;
  }

  public string getfilename() {
    return filename;
  }

  public long getfilesize() {
    return filesize;
  }

  public string download() throws exception{
    //给image字节流赋值
    string filerealpath = servletactioncontext.getservletcontext().getrealpath("/web-inf/classes/霉女.jpg");
    filename = filenameutils.getname(filerealpath);
    //方式一:中文文件要进行url编码
//   filename = urlencoder.encode(filename, "utf-8");
    filesize = new file(filerealpath).length();
    system.out.println(filename);
    image = new fileinputstream(filerealpath);
    return success;
  }
}

struts.xml配置文件:主要是对stream类型的结果进行配置

<struts>
  <constant name="struts.devmode" value="true" />
  <constant name="struts.ognl.allowstaticmethodaccess" value="true" />
    <action name="download" class="com.itheima.actions.downloadaction" method="download">
      <result type="stream">

        <param name="inputname">image</param><!--动作类中inputstream的字段名,需要在action中提供gettargetfile方法,返回inputstream-->
        <param name="contenttype">application/octet-stream</param><!--告诉浏览器响应头,文件的mime格式,调用action中的getcontenttype方法-->
        <!-- 在struts.xml中使用ognl表达式获取动作类中属性的值。 调用动作类中的 getfilename()-->
        <!-- 中文文件名编码:方式二.使用ognl表达式,调用urlencode的静态方法 -->
        <!-- 默认ognl调用静态方法是不行的,需要开启一个常量开关.struts.ognl.allowstaticmethodaccess=true -->
        <param name="contentdisposition">attachment;filename=${@java.net.urlencoder@encode(filename,'utf-8')}</param><!-- 告诉浏览器的下载方式-->
        <param name="contentlength">${filesize}</param>
      </result>
    </action>
  </package>
</struts>

拦截器和文件上传就写到这里了,好累,不过成就感满满的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。