Struts2 的文件下载

本文介绍如何在Struts2框架中实现文件下载功能,包括配置action和实现获取文件流及文件名的方法。

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

虽然说Struts2的下载是个小问题, 可是,有是忘记了,动手写还不容易。

网上的又是你C我的,我C你的,烦。

 

 

Struts2的下载其实很简单,只需要修改两个地方即可。

1、action的配置

 

 <action name="downloadfile" class="com.shenzhan.pro.util.DownloadfileAction">
           <result type="stream">
            <param name="contentType">application/octet-stream</param>
            <param name="inputName">inputStream</param>                                      <!-- 对应public InputStream getInputStream(); 返回文件流 -->
            <param name="contentDisposition">attachment;filename="${fileName}"</param>  <!-- public String getFileName();  返回文件名 -->
            <param name="bufferSize">4096</param>
           </result>
  </action>

 

 

 

 

2、两个方法 public InputStream getInputStream(); 返回文件流

                    public String getFileName();  返回提示的文件名

 

相应的Acption内容如下:

    package com.shenzhan.pro.util;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadfileAction extends ActionSupport {

private String filepath;  //这个是传入的文件路径,它在数据库里面是这样的 userupload/200912/20091215_104550_9381.rar                                                                       
 @Override
 public String execute() throws Exception {
  //这里可以设计权限
  if(filepath==null){
   return null;   //如果没有路径,返回空
  }
  return SUCCESS;
 }
 
 public InputStream getInputStream() throws Exception {
   String realpath="/"+filepath;  //必须是相对于根目录的绝对路径
   return ServletActionContext.getServletContext().getResourceAsStream(realpath);
 }
 
 public String getFileName(){
  int i=filepath.lastIndexOf("/")+1;
  return filepath.substring(i,filepath.length());
 }
 
 public String getFilepath() {
  return filepath;
 }

 public void setFilepath(String filepath) {
  this.filepath = filepath;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值