【文件处理】spring boot 文件处理

接收文件

java 复制代码
   @PostMapping
   public result<String> add(MultipartFile file) throws IOException {
 
     // 得到目标文件夹
       File directory = new File("file");
     //如果文件夹不存在就创建
      if(!directory.exists()){
            directory.mkdirs();
        }
     //文件名称
       String fileName = file.getOriginalFilename();
     //得到文件的存放路径  ---directory.getCanonicalPath() 文件夹全路径 --- File.separator:分隔符
       String filePath = directory.getCanonicalPath() + File.separator + fileName;  

     
      // 创建新文件对象,指定文件路径为新路径
      File desc = new File(filePath);
    
      // 将前端发过来的文件输送给新文件 完成存入
      file.transferTo(desc);
      return result.success("success");
   }

发送文件

java 复制代码
  @GetMapping("/{url}")
   public void pdf(@PathVariable String url, HttpServletResponse response) throws IOException {
    
     //文件所在文件夹
      File directory = new File("file");
  
     //文件路径
      String filePath = directory.getCanonicalPath() + File.separator + url;
     
    
      try {
         fileName = URLEncoder.encode(fileName, "UTF-8");
        //StringBuilder().append拼接字符串性能更高
         String header = new StringBuilder().append("attachment;filename=")
                 .append(fileName).toString();
        //响应的内容类型为"application/octet-stream",这是一种通用的二进制数据格式。
         response.setContentType("application/octet-stream");
        //      content-type 指示响应内容的格式
//
//      content-disposition 指示如何处理响应内容。
//
//      一般有两种方式:
//
//      inline:直接在页面显示
//      attchment:以附件形式下载
         response.addHeader("Content-disposition", header);
        //响应内容不会被压缩传输,而是直接发送给客户端。
         response.addHeader("Transfer-Encoding", null);
        //表示在响应完成后,连接将被立即关闭,不再进行后续的数据交换。
         response.addHeader("connection", "close");
      } catch (UnsupportedEncodingException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
      }
   //得到文件
      File file = new File(filePath);
      FileInputStream in = null;
      OutputStream out = null;
      try {
        //读取文件
         in = new FileInputStream(file1);
         out = response.getOutputStream();
         IOUtils.copy(in, out);
         out.flush();
      } catch (FileNotFoundException e) {
         e.printStackTrace();

      } catch (IOException e) {
         e.printStackTrace();

      } finally {
         IOUtils.closeQuietly(out);
         IOUtils.closeQuietly(in);
      }


   }
相关推荐
腾讯云云开发39 分钟前
腾讯云 CloudBase 登上 WAIC:我们为 Agent 重新设计了云的生产线
后端
Jelena1577958579240 分钟前
电商运营分析数据比价接口实战:多平台价格监控与智能决策系统
java·大数据·数据库
星栈1 小时前
从装一堆工具到看懂 Node 工程化思维:我的项目复盘记录
后端·node.js
65岁退休Coder1 小时前
LangChain v1.3.4 笔记 - 05 Agent 上下文记忆
后端
颜酱1 小时前
04 | 召回前置准备:搭好召回所需的四个数据库
前端·人工智能·后端
JaneConan1 小时前
鸿蒙 韶非 UI 系列:能力调用 startAbilityForResult,跳能力拿回参,鸿蒙能力路由入门
后端·harmonyos
晴空了无痕2 小时前
从 Go 基础到 K8s:一条可落地的 Go 服务端成长路线
开发语言·后端·golang·kubernetes
用户8356290780512 小时前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
神明不懂浪漫2 小时前
【第五章】Java中的继承与多态
java·开发语言
花椒技术2 小时前
原本要 2 天的服务端冒烟前置审查,为什么 3 分半就能出报告?|QA 质量交付实践(三)
后端·ai编程·测试