Struts2 文件下载

1. struts.xml

<action name="download" class="com.tvunetworks.center.tpc.util.DownloadAction">
   <result name="success" type="stream">
    <param name="contentType">application/octet-stream</param>
    <param name="inputName">inputStream</param>
    <param name="contentDisposition">attachment;filename="hello.txt"</param>
    <param name="bufferSize">4096</param>
   </result>
  </action>

 notice: <param name="contentDisposition">attachment;filename="${filename}"</param>

2.Action

package com.tvunetworks.center.tpc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class DownloadAction {
 private InputStream inputStream;
 public InputStream getInputStream() {
  return inputStream;
 }

 public void setInputStream(InputStream inputStream) {
  this.inputStream = inputStream;
 }

//如果名字使用了$

private String filename;

public String getFilename(){
  return filename;
 }

 public String execute() throws FileNotFoundException{

  inputStream=new FileInputStream(new File("C:\\a.txt"));

/* filename="C:\\a.txt";

*  inputStream=new FileInputStream(new File(filename));

*/
  return "success";
 }
}

3. 在URL输入:http://127.0.0.1:8080/myapp/download.action即能下载。

 

4、也可以下载自己在java写入的字符串,如下面的代码就能下载文件内容为my test的文件。

public String execute() throws FileNotFoundException{

 Strinig str="my test";
  inputStream=new ByteArrayInputStream(enStr.getBytes());

  return "success";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值