完整的 Spring Boot 下载文件示例代码

package com.alibaba.alpha.download;

import com.alibaba.alpha.mapper.UiTestCaseMapper;
import com.alibaba.alpha.model.UiTestCase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class DownloadController {
    @Autowired
    UiTestCaseMapper uiTestCaseMapper;

    /**
     * /downloadTestCase?testCaseId=${testCaseId}
     *
     * @param testCaseId
     * @param response
     * @throws Exception
     */
    @GetMapping("/downloadTestCase")
    public void downloadTestCase(Long testCaseId, HttpServletResponse response) throws Exception {
        // 1.用例数据
        UiTestCase UiTestCase = uiTestCaseMapper.selectByPrimaryKey(testCaseId);
        String tcName = UiTestCase.getName();
        // 2.文件存放路径
        String tmpDir = System.getProperty("user.home") + "/sidejson/";
        File tmpDirFile = new File(tmpDir);
        if (!tmpDirFile.exists()) {
            tmpDirFile.mkdir();
        }
        // 3.sideJson 文件
        String fileName = tmpDir + tcName;
        File sideJsonFile = new File(fileName);
        if (!sideJsonFile.exists()) {
            sideJsonFile.createNewFile();
        }
        FileWriter fileWritter = new FileWriter(fileName, true);
        fileWritter.write(UiTestCase.getSideJson());
        fileWritter.close();

        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文, 可以导入 iRecorder Web IDE中的 .side 文件
        String filename = URLEncoder.encode(tcName + ".side", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(sideJsonFile);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("Download successfully! " + fileName);
        } catch (Exception e) {
            System.out.println("Download failed! " + fileName);
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区