Feign接口获取文件流问题
文件下载
@GetMapping(value = "/v1/files/**/{file_name:.+}")public void downFile(@PathVariable("file_name") String fileName, HttpServletResponse response, HttpServletRequest request) {
// String uploadPath = IFlieServiceRpc.findByStrategyKey(uploadDir);String url = request.getServletPath();//获取urlurl = url.substring(url.lastIndexOf("files")).replace("files/", "");String uploadPath = null;String os = OSNameUtil.getOSname();if ("Windows".equals(os)) {uploadPath = winuploadDir;} else if ("Linux".equals(os)) {uploadPath = linuxuploadDir;}//截取时间戳String filename = "";//不带时间戳的文件名String ownFilePathString = "";//自定义文件路径if (url.lastIndexOf("/") > 0) {filename = url.substring(url.lastIndexOf("/") + 1);ownFilePathString = url.substring(0, url.lastIndexOf("/") + 1);} else {filename = url;}if (filename.indexOf("_") > 0) {filename = filename.substring(filename.indexOf("_") + 1);}String path = uploadPath + File.separator + url;String path1 = uploadPath + File.separator + ownFilePathString + filename;//判断文件是否存在File file2 = new File(path);if (!file2.exists()) {LOGGER.equals("文件不存在");throw new SBRException("文件不存在");}String getSm4Key = null;try {getSm4Key = PropertyUtil.getProperty("sm4");if (getSm4Key != null && !"".equals(getSm4Key)) {SM4Utils.decryptFile(path, path1, getSm4Key);} else {renameFile(path, path1);//path1=path;}} catch (IOException e1) {if (getSm4Key != null && !"".equals(getSm4Key)) {//解析后的文件需要删除File file = new File(path1);file.delete();}LOGGER.error("获取sm4报错,错误原因:" + e1);throw new SBRException("获取sm4报错,错误原因:" + e1);}File file = new File(path1);FileInputStream fis =null;try {if (file.exists()) {response.setHeader("Content-Disposition","attachment;filename=" + new String((file.getName()).getBytes("GB2312"), "ISO8859-1"));response.setContentLength((int) file.length());response.setContentType("application/octet-stream");// 定义输出类型fis = new FileInputStream(file);BufferedInputStream buff = new BufferedInputStream(fis);byte[] b = new byte[1024];// 相当于我们的缓存long k = 0;// 该值用于计算当前实际下载了多少字节OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载// 开始循环下载while (k < file.length()) {int j = buff.read(b, 0, 1024);k += j;myout.write(b, 0, j);}myout.flush();myout.close();buff.close();if (getSm4Key != null && !"".equals(getSm4Key)) {file.delete();}}} catch (Exception e) {if (getSm4Key != null && !"".equals(getSm4Key)) {//解析后的文件需要删除file.delete();}LOGGER.error("文件下载流错误,错误原因:" + e);throw new SBRException("文件下载流错误,错误原因:" + e);} finally {if(fis!=null){try {fis.close();fis=null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}try {if (getSm4Key == null && "".equals(getSm4Key)) {//没加密的文件需要处理renameFile(path1, path);}} catch (IOException e) {LOGGER.error("重命名失败,失败原因:" + e);throw new SBRException("重命名失败,失败原因:" + e);}}}
Feign接口调用
@FeignClient("prometheus-file")
public interface FileFeignClient {@GetMapping(value = "/file/api//v1/files/{file_name}",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)Response downFile(@PathVariable("file_name") String fileName);
}
获取Response中的文件流
/*** 将文件写入随机文件,并返回路径* @param fileName 文件名称* @return*/public String getFilePath(String fileName){InputStream inputStream = null;//获得文件流Response response =fileFeignClient.downFile(fileName);Response.Body body = response.body();String filePath ="";FileOutputStream fos = null;try {//获取response中的文件流inputStream = body.asInputStream();
// byte[] b = new byte[inputStream.available()];
// inputStream.read(b);//临时目录String folder=System.getProperty("java.io.tmpdir");int random = (int)(1+Math.random()*(10-1+1));String sj = String.valueOf(DateUtil.getCurrentDate().getTime());//临时路径+文件名称filePath = folder + sj+random+fileName.substring(fileName.lastIndexOf("."));//写入文件fos= new FileOutputStream(filePath);byte[] c = new byte[1024];int length;while((length= inputStream.read(c))>0){fos.write(c,0,length);}} catch (IOException e1) {e1.printStackTrace();}finally{try {inputStream.close();} catch (IOException e) {e.printStackTrace();}try {fos.close();} catch (IOException e) {e.printStackTrace();}}return filePath;}
读取文件内容,返回前台
@GetMapping(value = "/v1/notified_tasks/html")public Map<String,String> getHtmlBody(String notifiedTypeId){NotifiedType notifiedType = notifiedTypeService.findById(notifiedTypeId);//查找对应类型if(StringUtils.isEmpty(notifiedType.getNotifiedAttr())){Map<String,String> map = new HashMap<String, String>();map.put("htmlStr", "");map.put("fileName", notifiedType.getNotifiedAttr());return map;}//获取临时文件路径String filePath = getFilePath(notifiedType.getNotifiedAttr());String str = "";File file = new File(filePath);try {str = PoiUtils.officeToHtml(getUploadPath(), filePath);//获取html字符串file.delete();//删除临时文件} catch (Exception e) {file.delete();//删除临时文件e.printStackTrace();}if(str.equals("false")){str="";}Map<String,String> map = new HashMap<String, String>();map.put("htmlStr", str);map.put("fileName", notifiedType.getNotifiedAttr());return map;}
Feign接口获取文件流问题相关推荐
- axios 请求接口获取文件流数据导出数据到excel,解决乱码
axios.get("URL",{params:{data1:data1,data2:data2},headers: { 'Content-Type': 'application/ ...
- java根据url获取文件流
最近的一个需求需要根据一个mp3的链接获取文件流上传到内部的存储平台, 记录一下获取文件流的代码吧. pom文件 <dependency><groupId>org.apache ...
- 通过FeignClient获取文件流 steam is close问题
通过FeignClient获取文件流 steam is close问题 inputstream.read 报错 steam is close 原因:idea debug启动导致 解决办法:直接启动
- java使用feign接口下载文件
1.feign接口定义(注意:Response 导包) import feign.Response; /*** 导出定义*/@PostMapping(value="/xx/export&qu ...
- 2021-09-07-OSB学习(接口下载文件--流)
OSB学习(接口下载文件[流的形式]) 什么是使用流文件传输 1.我们要干什么 2.接口开发 2.1.控制台通过执行PL显示流文件信息 2.1.1.创建基本的目录结构 2.1.2.打开项目,然后创建B ...
- 任意java程序都可以是servlet吗_C#从Java servlet中获取文件流实现任意文件下载
目的: 从C#创建的客户端中向Java创建的servlet提交请求(不知道这是否算作严格的CS架构),servet返回一个文件流( 任意格式的文件 ),然后通过C#获取该文件流并保存到本地,使得文件可 ...
- java request 获取文件流_HttpRequest获取文件流,HttpResponse输出文件流
HttpResponse输出文件: Response.Clear(); Response.ContentType = "application/octet-stream"; //通 ...
- react集成react-pdf获取文件流预览下载pdf,展示电子签章
1.下载依赖包 代码如下(示例): npm install react-pdf 2.引入依赖包 代码如下(示例): import { Document, Page } from 'react-pdf' ...
- HttpRequest获取文件流,HttpResponse输出文件流
HttpResponse输出文件: Response.Clear(); Response.ContentType = "application/octet-stream"; //通 ...
最新文章
- js中match、replace方法中使用正则表达式
- android 镜像 制作工具,手机rom只制作-镜像工厂app下载2.8安卓最新版-西西软件下载...
- vue写进html,vue中html页面写入$t(‘’)怎么显示
- linux相对路径列出目录文件,linux – UNIX:列出目录中具有相对路径的文件
- 必须掌握的前端模板引擎之art-template
- 利用老毛头启动盘重装win7
- ffmpeg解码流程 turorial5详解
- python中的闭包与装饰器
- .NET中的Lambda表达式与匿名方法
- 研华自动驾驶计算机,研华全新发布宽温8TB NVMe SSD SQFlash 920系列 为自动驾驶应用保驾护航...
- 软件质量管理体系 type:pdf_普宁iso14001环境管理体系AAA信用等级认证
- iPad除了用来吃喝玩乐,还能能写代码了?
- 将进酒:《惜樽空》敦煌抄本
- qt开发之获取鼠标的相对位置和绝对位置
- I3C协议Single Data Rate(SDR)模式研读(一):总线配置Bus Configuration
- [译]深入ES6之箭头函数
- 比尔盖茨给青年人的十个忠告
- 几种食物绝对不能隔夜吃
- 诗经2 国风-周南-葛覃
- 【DP专辑】ACM动态规划总结