package com.tt.rhms.sys.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author xl
* 文件下载
*/
@RestController
public class DownloadFile {
@GetMapping("lz/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
Date date = new Date();
String time = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
String fileName = "";//下载后的文件名
String sourceFilePath = "D:\\download\\0.txt";//下载资源路径
String sourceFilePath1 = "D:\\download\\1.jfif";//下载资源路径
String sourceFilePath2 = "D:\\download\\2.jpg";//下载资源路径
String sourceFilePath3 = "D:\\download\\3.doc";//下载资源路径
String sourceFilePath4 = "D:\\download\\4.mp3";//下载资源路径
String suffix = sourceFilePath4.substring(sourceFilePath4.lastIndexOf("."));
fileName = time + suffix;
//配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buff = new byte[1024];
//创建缓冲输入流
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
//资源路径
bis = new BufferedInputStream(new FileInputStream(new File(sourceFilePath4)));
int read = bis.read(buff);
while (read != -1) {
outputStream.write(buff, 0, buff.length);
//outputStream.flush(); //报错:org.eclipse.jetty.io.eofexception,控制台报错,但功能正常使用
read = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
return "下载失败";
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "下载成功";
}
}