java 下载txt文件(页面代码+Java后台代码+下载工具类)

需求:页面有一个下载按钮,当点击下载的时候将页面表单数据下载到成为txt文件,并在网页直接下载该文件
在这里插入图片描述

1.页面(html)

下载一定要通过form表单的方式,js的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但form可以返回“流”类型的数据。

 <form class="form-horizontal" role="form" id="downloadForm" action="/exchange/download" method="post">
  <div class="form-group">
     //隐藏域 存放要下载的数据
    <input type="hidden"  id="downLoadData" value="" name="downLoadData"/>
    //页面展示要下载的数据
    <label class="col-sm-2 control-label no-padding-right bolder blue" id="exchangeCodeLabel"></label>
  </div>
  <div class="col-xs-12 col-sm-12 center" style="text-align: center">
    <button class="btn btn-success btn-sm" type="button" id="btn-donwn"><i class="fa fa-download" aria-hidden="true"></i>下载</button>
   </div>
  </form>

//js提交数据
//下载
$("#btn-donwn").click(function () {
  var downLoadDataTemp = $("#downLoadData").val();
  console.log("downloadData---"+downLoadDataTemp)
  // jQuery.post(prefix + '/exchangeCode/download',{downLoadData:downLoadDataTemp}, function(data){});
  $("#downloadForm").submit();
});
2.java代码
@PostMapping("/download")
@ResponseBody
public void downloadDxchangeCode (HttpServletRequest request, HttpServletResponse response, String downLoadData) {
  log.info("下载兑换码,downLoadData:{}", downLoadData);
  ExportTextUtil.writeToTxt(response, downLoadData.replaceAll(",", "\r\n"), "兑换码" + DateUtil.format(new Date(), "yyyyMMddHHmm"));
}
3.下载应用到工具类

ExportTextUtil.Java

package com.fp.coupon.utils.file;

import java.io.BufferedOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class ExportTextUtil {

  private static final Logger LOGGER = LoggerFactory.getLogger(ExportTextUtil.class);

  /**
   * 导出文本文件
   *
   * @param response
   * @param jsonString
   * @param fileName
   */
  public static void writeToTxt (HttpServletResponse response, String jsonString, String fileName) {//设置响应的字符集
    response.setCharacterEncoding("utf-8");
    //设置响应内容的类型
    response.setContentType("text/plain");
    //设置文件的名称和格式
    response.addHeader(
        "Content-Disposition",
        "attachment; filename="
            + AbstractFileUtil.genAttachmentFileName(fileName, "JSON_FOR_UCC_")
            + ".txt");//通过后缀可以下载不同的文件格式
    BufferedOutputStream buff = null;
    ServletOutputStream outStr = null;
    try {
      outStr = response.getOutputStream();
      buff = new BufferedOutputStream(outStr);
      buff.write(delNull(jsonString).getBytes("UTF-8"));
      buff.flush();
      buff.close();
    } catch (Exception e) {
      LOGGER.error("导出文件文件出错,e:{}", e);
    } finally {
      try {
        buff.close();
        outStr.close();
      } catch (Exception e) {
        LOGGER.error("关闭流对象出错 e:{}", e);
      }
    }
  }

  /**
   * 如果字符串对象为 null,则返回空字符串,否则返回去掉字符串前后空格的字符串
   *
   * @param str
   * @return
   */
  public static String delNull (String str) {
    String returnStr = "";
    if (!StringUtils.isEmpty(str)) {
      returnStr = str.trim();
    }
    return returnStr;
  }
}

AbstractFileUtil.Java

package com.fp.coupon.utils.file;

public abstract class AbstractFileUtil {

  /**
   * 生成导出附件中文名。应对导出文件中文乱码
   * <p>
   * response.addHeader("Content-Disposition", "attachment; filename=" + cnName);
   *
   * @param cnName
   * @param defaultName
   * @return
   */
  public static String genAttachmentFileName (String cnName, String defaultName) {
    try {
      cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
    } catch (Exception e) {
      cnName = defaultName;
    }
    return cnName;
  }
}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值