使用struts2控制文件上传

文件上传的准备:
上传文件显然要在表单中写上,这个文本域会在html页面中产生一个单行文本浏览框,以及一个浏览按钮同时还要设置*entype属性:
表单的enctype有三个属性,指定的是表单的编码方式,经常用的是multipart/form-data:这种方式会以为二进制流的形式来处理表单数据,这种编码方式会把文件域指定的内容也封装到参数内。
同时需要将method设置成post
一般写法是:
一旦将enctype设置成multipart/form-data形式,浏览器将使用二进制流的形式传送数据,这样服务器将不能通过request.getParameter();的方式请求数据,在后续的文章中,我们将会详细的说明该怎样自己写一个文件上传的类,今天先暂时搁置起来
实现文件上传:
新建一个jsp页面:内容如下

<body>
    <form action="upload.action" method="post" enctype="multipart/form-data">
        文件标题:<input type="text" name="title"/>
        选择文件:<input type="file" name="upload"/>
        <input type="submit" value="上传"/>
    </form>
</body>
</html>

新建一个action类:

package Action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

    //封装文件标题的请求参数的属性
    private String title;
    //封装上传文件域的属性
    private File upload;
    private String uploadContentType;//文件类型的属性
    private String uploadFileName;//文件名称
    private String savePath;//文件的上传路径

    public String execute() throws Exception{
        String title = getTitle();
        System.out.println(title);
        String save = getSavePath();
        System.out.println(save);//D:/test/upload
        String uploadName = getUploadFileName();
        System.out.println(uploadName);//20140530165433234.jpg
        String url = save+"/"+uploadName;
        System.out.println(url);//D:/test/upload/20140530165433234.jpg
        File file = new File(save);
        if(!file.exists()){
            file.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(url);
        File uplo = getUpload();
        FileInputStream fis = new FileInputStream(getUpload());
        byte [] buffer = new byte[1024];
        int len = 0;
        while((len = fis.read(buffer)) > 0){
            fos.write(buffer , 0 ,len);
        }
        return SUCCESS;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getSavePath() {
        return savePath;
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
}

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="GBK"/>
    <package name="liang" extends="struts-default">
        <action name="upload" class="Action.UploadAction">
            <!-- 设置要拦截的文件类型 -->
            <interceptor-ref name="fileUpload">
                <!-- 允许上传的文件时gif 和jpg   多个类型之间使用,隔开 -->
                <param name="allowTypes">image/gif,/image/jpeg</param>
                <!-- 允许上传的文件最大为20K -->
                <param name="maximunSize">20480</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"/>
            <!-- 动态设置Action的属性值 -->
           <param name="savePath">/upload</param>
            <!-- 配置Struts2默认的页面 -->
            <result>/success.jsp</result>
        </action>
    </package>  
</struts>   

注意:
我是在struts.xml参数中配置了/upload
所以最终上传的文件到的文件夹:/upload/20140530165433234.jpg(upload后面的是我上传的文件名)

一般我们是上传到项目的目录下:
下面对文件稍作修改保存在项目的文件下面:
仅仅修改action文件中的getSavePath()方法:

public String getSavePath() {
        HttpServletRequest request = ServletActionContext.getRequest(); 
        return request.getRealPath(savePath);
    }

这样:
控制台打印的就是:
F:\Users.metadata.me_tcat\webapps\test\upload : 这是要上传的文件目录,不存在创建
20140530165433234 (1).jpg :要上传的图片名
F:\Users.metadata.me_tcat\webapps\test\upload/20140530165433234 (1).jpg 完整目录

上传完成之后要跳转的success.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 'success.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">
  </head>
  <body>
    上传成功!<br/>
    <!--  根据上传文件的文件名,在页面中显示上传的文件-->
    <s:property value="+title"/><br/>
    <img src="<s:property value="'upload/'+uploadFileName"/>"/>
  </body>
</html>

至此一个单文件的上传实例已经写完,action中偶好多System.out.print()之类的语句,这里仅仅是为了看明白各个值到底是什么,也可以用debug模式运行,这样可以精简好多代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值