jsp action中附件下载的写法

//一些主要的包和类

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* 下载文件
* @return
* @throws UnsupportedEncodingException
*/

@Action(value="downloadAttachFile")
public String downloadAttachFile(){
  //从前台传过来的附件名字:格式是,“2006#系统测试.docx格式"
  String downloadName =wpyId+"#"+attachName;
  //传入的数据
  System.out.println(downloadName);
  try {
    OutputStream os = this.response.getOutputStream();

//OutputStream os = this.getResponse().getOutputStream();

    if (Util.isIE(this.request)) //判断客户端是否为IE
    {

//编码
      downloadName = URLEncoder.encode(downloadName, "UTF-8");
    }
    else
    {
      downloadName = new String(downloadName.getBytes("UTF-8"),"iso-8859-1");
    }
    //设置让浏览器弹出下载对话框的Header
    this.response.setContentType("application/x-download");
    this.response.addHeader("Content-Disposition","attachment;filename=\"" + downloadName + "\"");
    this.response.flushBuffer();
    //将前台的数据经过包装后(加了头数据,并经过编码)需要解码
    String downloadName1 =URLDecoder.decode(downloadName, "UTF-8");
    System.out.println(downloadName1);
    //解码的结果输出
    String bgFile=realPath + File.separator + downloadName1;

    FileInputStream fis = new FileInputStream(bgFile);
    Util.copyStrem(fis, os);
    fis.close();
    os.close();
    System.out.println("==========成功了!!===========");
  } catch (IOException e) {

  e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因
  System.out.println("==========出错了!!===========");
  }

  return NONE;
}

上一篇:【Spark 深入学习 04】再说Spark底层运行机制


下一篇:JavaWeb---总结(十六)JSP指令