package com.chint.tools;
import java.io.*;
/**
* @author wanglf3
* @date 2024-01-10
* @vsrsion 1.0
**/
public class FileDownloadUtil {
/**
* 输出指定文件的byte数组
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
if (os != null)
{
try
{
os.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fis != null)
{
try
{
fis.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
}
- 目标下载这个resource/DISCResult 下的这个pdf
- 使用上面的类的进行下载操作
@GetMapping("/getDiscPdfFile")
public void downloadPdf(String discResult, HttpServletResponse response, HttpServletRequest request) {
if (discResult == null) {
Result.error("传入DISC测评结果不能为空");
} else if (!(discResult.equals("C") ||
discResult.equals("CD") ||
discResult.equals("CS") ||
discResult.equals("D") ||
discResult.equals("DC") ||
discResult.equals("DI") ||
discResult.equals("I") ||
discResult.equals("ID") ||
discResult.equals("IS") ||
discResult.equals("S") ||
discResult.equals("SC") ||
discResult.equals("SI") ||
discResult.equals("34-Ability")
)) {
Result.error("传入DISC测评结果没有对应的类型");
}
String fileNameStr = null;
if (discResult.equals("34-Ability")) {
fileNameStr = "34-Ability.pdf";
} else {
fileNameStr = "DISC-ResultReport-" + discResult + ".pdf";
}
String pdfFilePath = DiscResultController.class.getResource("/DISCResult/" + fileNameStr).getFile();
try {
FileDownloadUtil.writeBytes(pdfFilePath, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
log.error("下载文件失败", e);
}
}
- 最后用postman测试
下载完成