博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Apache Httpclient访问Spring rest接口下载文件
阅读量:7227 次
发布时间:2019-06-29

本文共 2573 字,大约阅读时间需要 8 分钟。

hot3.png

1.编写 rest接口,该接口将文件读入到流中并通过ResponseEntity对象返回

@RequestMapping(value="/file",method=RequestMethod.GET)public ResponseEntity
getFile(@RequestParam Integer id){ //设置response返回头部信息 HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must- revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); FileInputStream input=null; File file=null; long len=0l; try { //通过主键ID获取文件对象 FileData data=fileMapper.selectByPrimaryKey(id); //获取文件存储的路径 String filePath=data.getFilePath(); //通过Paths获取文件 file=Paths.get(filePath).toFile(); input=new FileInputStream(file); len=file.length(); } catch (Exception e) { e.printStackTrace(); } //设置返回实体的头部、长度及类型 return ResponseEntity .ok() .headers(headers) .contentLength(len) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(input));}

2.应用二使用httpclient发送请求获取文件流,然后将文件流写入到文件中实现文件下载功能

@RequestMapping(value="/file/download/{id}",method=RequestMethod.GET)public OperationResult downloadFile(@PathVariable(value="id") Integer id,HttpServletResponse response){//根据主键ID从数据库中查询文件信息Map
originalDataMap=fileMapper.findFileByPrimaryKey(id);//获取文件的名称(包含后缀)String oldFileName=String.valueOf(originalDataMap.get("original_title"));byte[] buffer= new byte[1024]; //char[] buffer= new char[1024]; int len=-1; //创建httpClient客户端 CloseableHttpClient httpClient=HttpClients.createDefault(); //创建httpGet发送请求获取文件 HttpGet httpGet=new HttpGet("http://localhost:8080/test?id="+id); //将文件读入到输入流中 try(CloseableHttpResponse httpResponse=httpClient.execute(httpGet); InputStream input=httpResponse.getEntity().getContent(); OutputStream output=response.getOutputStream(); ){ //设置响应头 response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(oldFileName, "UTF-8")); //从输入流中读取文件 while((len=input.read(buffer))!=-1){ //将buffer数组写入到文件中,从0开始写入的长度为实际读取到的长度len,如果使用write(buffer);会出现中文乱码及图像变模糊的问题 output.write(buffer,0,len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}

转载于:https://my.oschina.net/airship/blog/1507163

你可能感兴趣的文章
Javascript通过Name调用Function
查看>>
统计当前在线用户数量
查看>>
IntelliJ IDEA 乱码解决方案 (项目代码、控制台等)
查看>>
PHP项目记录
查看>>
.net面试题系列文章七(附答案)
查看>>
FastSocket
查看>>
ionic $ionicSlideBoxDelegate 滑动框事件
查看>>
点击文字,把input type="radio"也选中
查看>>
第一章 Java多线程技能
查看>>
Java 集合系列-第八篇-Map架构
查看>>
springmvc 3.2 @MatrixVariable bug 2
查看>>
React-Native PanResponder手势识别器
查看>>
IOS11 光标错位问题
查看>>
如何设计用户登录
查看>>
linux安装mysql5.7.19
查看>>
Zookeeper+ActiveMQ 集群实现
查看>>
加权有向图问题2----多源最短路径问题(Floyd算法)和关键路径算法
查看>>
logback logback.xml常用配置详解(三) <filter>
查看>>
KgMall B2B/B2B2c/C2C版店铺商号初始化
查看>>
Linux内核的ioctl函数学习
查看>>