JAVA将字符串作为txt下载

 后端写法:

package gov.zhbs.web;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 将字符串作为txt下载
 * </p>
 * <p>
 * Copyright:2022.All rights reserved.
 * </p>
 * <p>
 * Company:Zsoft
 * </p>
 * <p>
 * CreateDate:2022-01-21 11:54
 * </p>
 *
 * @author YuGongWen
 * @history Mender:YuGongWen;Date:2022-01-21 11:54;
 */
@RequestMapping("/download")
@Controller
public class DownloadController {

    /**
     *  将字符串作为txt下载
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/downloadJson", method = RequestMethod.GET)
    public void downloadBizServiceEntityJson(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String in = "这是一段需要下载字符串!!!!";

        long timeMillis = System.currentTimeMillis();
        // 构造一个临时文件全路径
        String fullName = request.getSession().getServletContext().getRealPath("/") + "/resourceFileCache/" + timeMillis +"_json.txt";
        // 通过临时文件全路径 new一个File对象
        File file = new File(fullName);
        // 将字符串写入这个临时文件中
        FileUtils.writeStringToFile(file,in);
        // 读取这个文件为 byte[]
        byte[] fileDatas = FileUtils.readFileToByteArray(file);
        // 删除临时文件
        FileUtils.deleteQuietly(file);

        // 将文件内容 byte[],通过 response 返回给客户端进行下载
        if(fileDatas != null && fileDatas.length > 0){
            try {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition","attachment; filename=json.txt");
                response.setHeader("Content-Length", String.valueOf(fileDatas.length));
                response.getOutputStream().write(fileDatas);
                response.flushBuffer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


}

前端写法:

<div id="input" class="eform-input ">
	<a target="_blank" class="btn form-control" href="${ctx }/download/downloadJson">点击下载</a>
</div>

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值