struts2的手动上传详细讲解

1. jar包的引入:

在lib文件夹下引入commons.io-2.2.jar和commons-fileupload-1.3.1.jar两个JAR包,版本可以根据自己的需要自行选择
这里写图片描述

2.上传的JSP页面

form表单上传必需的两个属性method=”post”,enctype=”multipart/form-data”,
enctype=”multipart/form-data”:以二进制的数据格式来传输

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> 
  <body>
    <P>上传头像</P>
    <form action="upload.action" method="post" enctype="multipart/form-data">
        <input type="file" name="myIcon"/>
        <input type="submit" value="提交"/>
    </form>
  </body>
</html>
3.配置struts.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>
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="struts.custom.i18n.resources" value="message"></constant>
    <package name="struts2" extends="struts-default">
        <action name="upload" class="com.package.UploadAction" method="upload" >
            //文件保存的相对路径,在java页面需要获取文件的绝对路径
            <param name="savePath">/upload</param>
            //文件允许上传文件的类型(截取后缀名方式判断是否允许)
            <param name="allowTypes">ico,jpg,png</param>
            //文件上传大小上限
            <param name="maxSize">10241024</param>
            <result name="success">/uploadok.jsp</result>
            <result name="input">/upload.jsp</result>
        </action>   
    </package>
</struts> 
4.uploadAction.java文件
package com.check.project;

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 static final long serialVersionUID = 1L;
    //上传页面传进来的name的值
    private File myIcon;
    //命名格式xxxFileName,xxxContentType
    private String myIconFileName;
    private String myIconContentType;
    private String allowTypes;
    private long maxSize;
    //文件上传的保存路径
    private String savePath;

    public String getAllowTypes() {
        return allowTypes;
    }
    public void setAllowTypes(String allowTypes) {
        this.allowTypes = allowTypes;
    }

    public File getMyIcon() {
        return myIcon;
    }
    public void setMyIcon(File myIcon) {
        this.myIcon = myIcon;
    }
    public String getMyIconFileName() {
        return myIconFileName;
    }
    public void setMyIconFileName(String myIconFileName) {
        this.myIconFileName = myIconFileName;
    }
    public String getMyIconContentType() {
        return myIconContentType;
    }
    public void setMyIconContentType(String myIconContentType) {
        this.myIconContentType = myIconContentType;
    }
    public long getMaxSize() {
        return maxSize;
    }
    public void setMaxSize(long maxSize) {
        this.maxSize = maxSize;
    }
    public String getSavePath() {
        return savePath;
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    //获取到文件名,截取文件的后缀名,判断是否符合上传类型
    public Boolean subExtentionName(String[] types){
        //获取后缀名前"."的索引
        int begin = myIconFileName.lastIndexOf(".");
        //substring()方法截取后缀名
        String ExtentionName=getMyIconFileName().substring(begin+1);
        //遍历配置的类型,判断类型是否合法
        for(String type : types){
            if(type.equals(ExtentionName)){
                return true;
            }
        }       
        return false;
    }
/*  //直接通过文件类型来判断文件是否合法image/png,image/gif,image/jpeg
    public Boolean typeFilter(String[] types){
        //获取文件类型
        String fileType = getMyIconContentType();
        //遍历文件允许的类型,判断是否合法
        for (String type : types) {
            if (type.equals(fileType)) {
                return true;
            }
        }
        return false;
    }
*/
    //校验文件
    public void validate(){
        String[] types = getAllowTypes().split(",");
        if(!subExtentionName(types)){
            this.addFieldError("myIcon", "您上传的文件格式有误!");
        }

        if(getMyIcon().length() > getMaxSize()){
            this.addFieldError("myIcon", "您上传的文件太大了!");
        }
    }
    //开始上传文件
    public String upload() throws Exception{
        try{
            //获取上传的文件需要保存的绝对路径
            String path = ServletActionContext.getServletContext().getRealPath(getSavePath());
            //判断文件夹是否存在不存在自动创建
            File newFile  = new File(path);
            if(!newFile.exists()){
                newFile.mkdir();
            }
            //创建文件等待上传文件内容的写入
            File file = new File(path,getMyIconFileName());
            //创建输出流将buffer中的数据写进创建的文件中
            FileOutputStream fos = new FileOutputStream(file);
            //创建上传文件的输入流,将源文件写到buffer中
            FileInputStream fis = new FileInputStream(getMyIcon());
            //创建缓存区
            byte[] buffer = new byte[1024];
            //将buffer中的数据循环写入到新创建的文件中
            while(true){
                int len = fis.read(buffer, 0, buffer.length);
                if(len == -1){
                    break;
                }
                fos.write(buffer,0,len);
            }
            //一定要关闭输入输出流释放占用的资源
            fos.close();
            fis.close();

        }catch (Exception e) {
            e.printStackTrace();
        }   
        System.out.print("上传成功...");
        return SUCCESS;
    }
}

5.希望可以帮助到大家,小编也是初学者,互相学习,谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值