@ApiOperation("excel模板下载")
@PostMapping("/file/excelDownload")
public void excelDownload(HttpServletResponse response) {
String fileUrl = filePath+ File.separator+"标准模板.xlsx";
DownloadUtil.download(response,fileUrl);
}
public class DownloadUtil {
private static String encoding = "utf-8";
public static void download(HttpServletResponse response, String filePath){
File file = new File(filePath);
download(response, file, null, encoding);
}
public static void download(HttpServletResponse response, File file, String fileName, String encoding) {
if(file == null || !file.exists() || file.isDirectory()){
return;
}
if (StringUtils.isBlank(fileName)) {
fileName = file.getName();
}
try {
InputStream is = new FileInputStream(file);
download(response, is, fileName, encoding);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void download(HttpServletResponse response, InputStream is, String fileName, String encoding){
if(is == null || StringUtils.isBlank(fileName)){
return;
}
BufferedInputStream bis = null;
OutputStream os = null;
BufferedOutputStream bos = null;
try{
bis = new BufferedInputStream(is);
os = response.getOutputStream();
bos = new BufferedOutputStream(os);
response.setContentType("application/octet-stream;charset=" + encoding);
response.setCharacterEncoding(encoding);
response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, encoding));
byte[] buffer = new byte[1024];
int len = bis.read(buffer);
while(len != -1){
bos.write(buffer, 0, len);
len = bis.read(buffer);
}
bos.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
if(bis != null){
try{
bis.close();
}catch(IOException e){}
}
if(is != null){
try{
is.close();
}catch(IOException e){}
}
}
}
public static String getEncoding() {
return encoding;
}
public static void setEncoding(String encoding) {
DownloadUtil.encoding = encoding;
}
}