当前位置:   article > 正文

java读本地文件并通过接口返回文件流_java 接口返回文件流

java 接口返回文件流

this.historicalSchemePath//本地存储的地址比如c:/ 

@GetMapping(value = "/getsCheme")
public void getsCheme(@RequestParam(name="fid") String fid,
                        HttpServletRequest req,
                 HttpServletResponse resp) {
   CtglPlaninfo ctglPlaninfo=ctglPlaninfoMapper.queryRecord(fid);
   String fapath="//"+ctglPlaninfo.getFapath();
   // 通过id 查询 数据表 地址
   //获取配置文件地址
   // 文件地址 = 配置文件地址+数据表地址
   File file=new File(this.historicalSchemePath);
   if(!file.exists()){
      try {
         file.mkdirs();
      }catch (Exception e){
         e.printStackTrace();
      }
   }
   File file2=new File(this.historicalSchemePath+fapath);
   //获取文件名
   String fileName=fapath.substring(fapath.lastIndexOf("//")+2);
   if(file2.exists()){
      FileInputStream in=null;
      HttpServletResponse response=resp;
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/octet-stream;charset=utf-8");
      response.setHeader("Content-disposition","attachment;filename="+fileName);

      try{
         in=new FileInputStream(this.historicalSchemePath+fapath);
         byte[]a=new byte[1024];
         int b;
         while ((b=in.read(a))!=-1){
            response.getOutputStream().write(a,0,b);
         }
      }catch (Exception e){
         e.printStackTrace();
      }finally {
         if(null!=in){
            try{
               in.close();
            }catch (IOException e2){
               System.out.println("关闭输入流错误");
            }
            try{
               response.getOutputStream().close();
            }catch (IOException e){
               System.out.println("输出流关闭错误");
            }
         }
      }
   }else {
      try {
         resp.getWriter().println("查不到文件");
      }catch (IOException e){
         System.out.println("resp返回前端信息异常");
      }

   }
}
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号