4.struts2中的文件上传,下载

Struts2中文件的上传下载,是借用commons里面的包实现文件的上传,需要导入两个jar

  commons-fileupload-1.2.2.jar

  commons-io-2.0.1.jar

实现的时候你可以使用s标签,也可以使用普通的表单标签步骤大概如下:

  使用s标签的话,先导入标签

  修改form 表单的enctype属性

  编写action(利用IO流进行上传文件)

  1.使用s标签的话,先导入标签

<%@ taglib prefix="s" uri="/struts-tags" %>

  2.修改enctype属性

  <body>
    <s:form action="file2" method="post" enctype="multipart/form-data">
        <s:file name="photo"></s:file></br>
        <s:submit value="提交"></s:submit>
    </s:form>
  </body>

  3.编写action(利用IO流进行上传文件)

    属性:

private File photo;//文件位置
    private String photoFileName;// 文件名
    private String photoContentType;// 文件类型

    上传方法:

public String execute() throws IOException {
        // 传到哪里(文件长传后的路径)
        ServletContext servletContext = ServletActionContext
                .getServletContext();
        String path = servletContext.getRealPath("/img/" + photoFileName);
        System.out.println("文件路径:" + path);
        // 去读取原文件的位置
        FileInputStream in = new FileInputStream(photo);
        // 写入你定义的文件上传的路径
        FileOutputStream out = new FileOutputStream(path);
        // 写的过程
        byte[] buffer = new byte[1024];
        int leng = 0;
        // 就是已经读取文件完成
        while ((leng = in.read(buffer)) != -1) {
            out.write(buffer, 0, leng);
        }
        in.close();
        out.close();
        return "success";
    }

 

  文件下载直接贴代码:

  在配置文件中的type属性使用stream作为type的结果类型

  下载需要设置的参数:

    contentType:

    Contentlength:

    inputName:指定getter定义的那个属性的名字,默认是inputStream

    BufferSize:缓存大小

    allowCache:是否允许缓存

    contentCharSet:指定下载的字符集,在配置文件中配置一个type为stream的action

    struts2配置文件

<!--下载的配置  -->
        <action name="filedownload" class="com.etc.action.FileDownLoadAction" method="filedownload">
            <result type="stream">
                <param name="bufferSize">2048</param>
            </result>
        </action>

    下载的代码(get,set方法记得生成)

private String contentType;
    private String contentDisposition;
    private InputStream inputStream;
    private long contentLength;
    public String filedownload() throws IOException{
        contentType="text/html";//指定文件的类型
        contentDisposition="attachment;filename=index.html";//下载的提示框
        ServletContext servletContext=ServletActionContext.getServletContext();
        //告诉文件在哪里
        String filename=servletContext.getRealPath("/img/index.html");
        //去读文件
        inputStream=new FileInputStream(filename);
        contentLength=inputStream.available();
        return "success";
    }

 

转载于:https://www.cnblogs.com/huaixiaoz/p/5937742.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值