【文件处理】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);
      }


   }
相关推荐
爱勇宝1 小时前
从 Ctrl+CV 到 Enter:程序员正在失去什么
前端·后端·程序员
码事漫谈1 小时前
EdgeOne Makers + WorkBuddy:零基础也能快速搭建可上线的 AI 智能体(附图文教程)
后端
像我这样帅的人丶你还2 小时前
Java 后端详解(四):分页与搜索
java·javascript·后端
她的男孩2 小时前
数据权限为什么不能只靠注解?Forge 的 Mapper 层 SQL 改写源码拆解
java·后端·架构
烤代码的吐司君2 小时前
Redis 数据结构 ZSet, BIT, HyperLogLog,Geo 空间数据
redis·后端
苏三说技术2 小时前
为什么越来越多的人使用FastAPI?
后端
JavaGuide2 小时前
比 iTerm2 更适合 Claude Code/Codex 的终端,我换成 Ghostty 了
人工智能·后端
tntxia3 小时前
Mybatis的日志输入
java
DyLatte3 小时前
AI 时代,最危险的不是被替代,而是努力不沉淀
前端·后端·程序员
神奇小汤圆3 小时前
架构师必备:CPU使用率不均匀排查
后端