1.编写 rest接口,该接口将文件读入到流中并通过ResponseEntity对象返回
@RequestMapping(value="/file",method=RequestMethod.GET)public ResponseEntitygetFile(@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从数据库中查询文件信息MaporiginalDataMap=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(); }}