Struts2.5文件上传和下载详解(一)

本文详细介绍了Struts2.5中实现文件上传和下载的步骤,包括所需jar包、表单设置、Action配置、拦截器过滤、错误处理及国际化信息。特别指出,IE和火狐浏览器对文件类型的翻译差异可能导致上传问题,以及如何定位上传文件在服务器的保存位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天了解了文件的上传与下载,遇到了很多的问题,解决了一天终于也算是懂了一些。现在来分享一下。

文件的上传


1、要实现Struts2.5的文件上传功能,必须包含两个jar文件:commons-io-2.4.jarcommons-fileupload-1.3.3.jar


2、在jsp文件的表单中,表单的method设置为:POSTenctype设置为multipart/form-data(此时浏览器采用二进制流的方式来处理表单数据)

例:uploadForm.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:form action="upload" method="post" 
 enctype="multipart/form-data">
 <s:file name="upload" label="选择文件"></s:file>
 <s:submit value="上传"></s:submit>
</s:form>
</body>
</html>

3、若表单中file文件的name属性为“xxx”,则Action中必须使用三个成员变量去封装该文件域的信息
(1)类型为File的xxx成员变量封装对应文件内容
(2)类型为String的xxxFileName成员变量封装了对应的文件名
(3)类型为String的xxxContentType成员变量封装了文件域对应的文件类型(通常使用在配置Action中去限制上传文件的类型)

例:UploadAction.java

package gzy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction  extends ActionSupport{
    //封装上传文件域的成员变量
    private File upload;
    //封装上传文件类型的成员变量
    private String uploadContentType;
    //封装上传文件名的属性
    private String uploadFileName;
    private String savePath;
    public void setSavePath(String value){
        this.savePath=value;
    }
    public String getSavePath(){
        return ServletActionContext.getServletContext()
                .getRealPath(savePath);
    }
    public void setUpload(File upload){
        this.upload=upload;
    }
    public File getUpload(){return this.upload;
    }
    public void setUploadContentType(String uploadContentType){
        this.uploadContentType=uploadContentType;
    }
    public String getUploadContentType(){
        return this.uploadContentType;
    }
    public void setUploadFileName(String uploadFileName){
        this.uploadFileName=uploadFileName;
    }
    public String getUploadFileName(){
        return this.uploadFileName;
    }
    public String execute()throws Exception{
         File f=new File(getSavePath());
         if(!f.exists())
             f.mkdirs();//若文件不存在,则创建
        FileOutputStream fos=
                new FileOutputStream(new File(f,getUploadFileName()));
        FileInputStream fis=new FileInputStream(getUpload());
        byte[] buffer=new byte[1024];
        int len=0;
        while((len=fis.read(buffer))>0)
            fos.write(buffer,0,len);
        fos.close();
        fis.close();
        return SUCCESS;
    }
}

4、配置上传文件的Action
如上述例子中保存文件的路径,需要在struts.xml中动态的设置”savePath”属性值。
拦截器实现文件过滤:拦截器可以过滤不被允许上传的文件和超出上传大小的文件
Struts2的拦截器为fileUpload,有指定的两个参数
allowedType:允许上传文件的类型,文件类型以“,”隔开
maximumSize:指定允许上传文件的大小,单位字节
注意:使用该拦截器时,必须显示配置引用Struts的默认拦截器栈:defaultStack。并且fileUpload拦截器配置在defaultStack之前

例:struts.xml

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE struts PUBLIC    
            "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"    
    "http://struts.apache.org/dtds/struts-2.5.dtd">  
<struts>
    <!-- 指定默认编码集 -->
    <constant name="struts.i18n.encoding" value="UTF-8"/>  
    <!-- 开发阶段可以打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true"/>
    <!-- 是否开启方法调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
    <package name="gzy" namespace="/" extends="struts-default">
        <action name="upload" class="gzy.UploadAction" >
        <interceptor-ref name="fileUpload">
        <param name="allowedTypes">image/png
                    ,image/gif,image/jpeg,image/pjpeg,image/x-png</param>
        <param name="maximunSize">2000</param>
        </interceptor-ref>
        <interceptor-ref name="defaultStack"/>
        <!-- 动态设置Action的属性值 -->
        <param name="savePath">/uploadFiles</param>
        <result name="input">/uploadForm.jsp</result>
        <result >/succ.jsp</result>
        </action> 
    </package>  
</struts>    

注意:我曾遇到上传.jpg文件失败,后查资料发现:IE浏览器会把 jpg、jpeg翻译成image/pjpeg,png翻译成image/x-png 。而火狐则把jpg、jpeg翻译成image/jpeg,png翻译成image/png


5、输出错误的显示。如果上传失败,则系统返回逻辑视图,系统默认的显示提示信息为英文。可以用国际化信息去替换它。
国际化信息的key属性为:
struts.messages.error.file.too.large:文件太大
struts.messages.error.content.type.not.allowed:文件类型不是允许的类型

例:mess.properties(在/src目录下)

struts.messages.error.content.type.not.allowed=您上传的文件类型只能是图片文件!
struts.messages.error.file.too.large=您要上传的文件太大,请重新选择!

再通过native2ascii命令处理该文件(若读者不会,可参考博主另一篇文章native2ascii处理文件

并且在struts.xml中配置该国际化资源
<constant name="struts.custom.i18n.resources" value="mess"/>


6、succ.jsp内容为上传成功

(文件类型不符)
这里写图片描述
这里写图片描述

(上传成功)
这里写图片描述
这里写图片描述

注意:若想知道jpg文件上传到服务器哪,可打印上传的真实路径

         System.out.println(getSavePath());//上述Action已经写好该方法去返回真实路径

博主的路径为:
F:\JavaWeb\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Chapter4_09\uploadFiles

这里写图片描述

以上是在Eclipse环境下,但若在Tomcat服务器下去部署该Web应用,那么上传文件保存在Web应用下了

这里写图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值