java读取resource下的文件 下载
点击查看代码
public void downloadKsxxYzyTemplate(HttpServletRequest request, HttpServletResponse response) {
try {
// FileDownloadUtils.downloadFileFromResource(response, YZYMB_NAME,YZYMB_URL);
FileDownloadUtils.downloadFileFromResource(response,
"一志愿考生名单导入参考模板.dbf","/template/一志愿考生名单导入参考模板.dbf",
request);
}catch (IOException e) {
log.error("一志愿考生信息参考模板下载失败:{}",e);
throw new ServiceException(2,"一志愿考生信息参考模板下载失败");
}
}
public static void downloadFileFromResource(HttpServletResponse response,
String fileName,
String classPathResourcePath,
HttpServletRequest request) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(classPathResourcePath);
if (!classPathResource.exists()) {
throw new RuntimeException("找不到源文件!");
}
InputStream inputStream = classPathResource.getInputStream();
/* response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName()));
response.setContentType("application/octet-stream");
OutputStream outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
// outputStream.close();
inputStream.close();*/
// ClassPathResource classPathResource = new ClassPathResource("/excel/机构导入模板.xlsx");
// InputStream inputStream = classPathResource.getInputStream();
//生成目标文件, 上面那种直接读取再输出dbf会打不开文件
File somethingFile = File.createTempFile("Topic_Template", ".dbf");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
InputStream in = new FileInputStream(somethingFile);
getFileContent(in, fileName, response, request);
}
public static void getFileContent(InputStream inputStream, String name, HttpServletResponse response, HttpServletRequest request) {
// 清空response
response.reset();
try {
InputStream in = inputStream;
response.setHeader("Content-Length", String.valueOf(in.available()));
byte[] buffer = new byte[in.available()];
//不加打开会文件损坏
in.read(buffer);
in.close();
String userAgent = request.getHeader("User-Agent");
/*String fileName;
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
fileName = URLEncoder.encode(name, "UTF-8");
} else {
// 非IE浏览器的处理:
fileName = new String(name.getBytes("UTF-8"), "ISO-8859-1");
}*/
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(name, StandardCharsets.UTF_8.displayName()));
// 设置response的Header
// response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/x-dbf");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
前端:
点击查看代码
exportTemplate = () => {
const { templateUrl } = this.props;
certificateTemplate(templateUrl, {},{},(res) => {
let fileName = res.headers['content-disposition'].split(';')[1].split('filename=')[1];
const aLink = document.createElement('a');
document.body.appendChild(aLink);
aLink.style.display = 'none';
const objectUrl = URL.createObjectURL(res.data);
aLink.href = objectUrl;
aLink.download = decodeURI(fileName);
aLink.click();
document.body.removeChild(aLink);
});
// 模板
export function certificateTemplate(url, params, permission = auth.template,callback) {
downloadFile(url, params, {headers:{permission}}).then(response=>{
callback(response);
}).catch(err=>{
message.error("文件下载失败"+err);
})
}
/**
* add by ych
* 下载文件,二进制流
* @param {*} url 接口url
* @param {*} params 查询参数
* @param {*} config
*/
export function downloadFile(url, params, config = {}) {
return new Promise((resolve, reject) => {
axios
.post(url, params, { responseType: 'blob', ...config })
.then(res => {
resolve(res);
})
.catch(err => {
reject(err.data);
});
});
}
posted on 2024-02-27 10:38 HeavenTang 阅读(385) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2023-02-27 CountDownLatch和ExecutorService 线程池cachedThreadPool.submit