当前位置: 首页 > article >正文

Spring Boot 实现多文件上传

文件上传

Spring Boot代码

  1. 代码结构:
    image-20230308100726724

  2. Controller层

    package com.yqifei.upload.controller;
    
    import io.swagger.annotations.Api;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    /**
     * @ClassName UploadController
     * @Description TODO
     * @Author jiangyuntao
     * @Data 2023/3/7 23:52
     * @Version 1.0
     * @Email yuntaojiang@foxmail.com
     */
    
    @RestController
    @CrossOrigin
    @RequestMapping("/posts")
    @Api(tags = "文件上传控制器")
    public class UploadController {
    
    /*
    http://localhost:8088/swagger-ui.html#
    */
        @PostMapping(value="/upload")
        @CrossOrigin
        public List<String> fileload(@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest request) throws IOException {
            System.out.println(file.length);
            String savaLaction="d:/data/";
            String fileSaveName;
            List<String> imageUri = new ArrayList<>();
            for (MultipartFile multipartFile:file) {
                System.out.println("文件"+multipartFile.getOriginalFilename());
                fileSaveName = UUID.randomUUID().toString()+multipartFile.getOriginalFilename();
                multipartFile.transferTo(new File(savaLaction,fileSaveName));
                String res = request.getScheme()+"://"+request.getServerName()+":"+"8080"+savaLaction+"/"+fileSaveName;
                imageUri.add(res);
            }
            System.out.println(imageUri);
            return imageUri;
        }
    
    }
    
    
  3. 跨域拦截器配置

    package com.yqifei.upload.utils;
    
    import org.springframework.context.annotation.Configuration;
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    @WebFilter(filterName = "CorsFilter")
    @Configuration
    public class CorsFilter implements Filter {
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            chain.doFilter(req, res);
        }
    }
    
    
  4. application.properties配置

    # 应用名称
    spring.application.name=upload
    # 应用服务 WEB 访问端口
    server.port=8088
    
    spring.web.resources.static-locations=file:d:/data/
    
    spring.servlet.multipart.max-request-size=50MB
    spring.servlet.multipart.max-file-size=50MB
    
  5. 前端页面

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>Multiple File Upload</title>
      </head>
      <body>
        <h1>Multiple File Upload</h1>
        <form>
          <input type="file" id="fileInput" multiple />
          <button type="button" onclick="uploadFiles()">Upload</button>
        </form>
        <div id="progress"></div>
        <div>图片返回值地址:</div>
        <div id="result"></div>
      </body>
      <script>
        function uploadFiles() {
          const files = document.getElementById("fileInput").files;
          const xhr = new XMLHttpRequest();
          const formData = new FormData();
    
          for (let i = 0; i < files.length; i++) {
            formData.append("file", files[i]);
          }
    
          xhr.open("POST", "http://localhost:8088/posts/upload");
          xhr.upload.addEventListener("progress", function (event) {
            if (event.lengthComputable) {
              const percent = Math.round((event.loaded / event.total) * 100);
              const progress = document.getElementById("progress");
              progress.innerHTML = "Upload progress: " + percent + "%";
            }
          });
          xhr.addEventListener("load", function (event) {
            const response = JSON.parse(event.target.responseText);
            console.log(response);
            // 在HTML页面上找到需要显示响应结果的元素
            const resultElement = document.getElementById("result");
            // 更新元素的文本内容为服务器返回的值
            resultElement.textContent = response;
          });
          xhr.send(formData);
        }
      </script>
    </html>
    
    
    
  6. 效果展示

    image-20230308101306807

  7. 获取图片的url并且读取图片
    image-20230308132353937

    1. 修改tomcat的server.xml文件

      image-20230308132157875

      加上下面这句

      <Context docBase ="/home/springbootVue/files" path ="/home/springbootVue/files" debug ="0" reloadable ="true"/>
      // 	docBase代表文件路径,path是浏览器访问时的路径。
      // 若自己创建的文件夹在tomcat目录的webapps中,不同之处: docBase直接写文件夹文字即可(注意:没有/) 例如 docBase ="home/springbootVue/files"
      

http://www.kler.cn/a/3105.html

相关文章:

  • 阿里巴巴Qwen团队发布AI模型,可操控PC和手机
  • shell脚本批量修改文件名之方法(The Method of Batch Modifying File Names in Shell Scripts)
  • 指针的介绍3后
  • HarmonyOS DevEco Studio模拟器点击运行没有反应的解决方法
  • HTML<kbd>标签
  • 分布式版本控制系统:Git
  • “提效”|教你用ChatGPT玩数据
  • Android 基础功能例子
  • 智能零售柜商品检测软件(Python+YOLOv5深度学习模型+清新界面)
  • 自定义类型 (结构体)
  • C# 支付宝接口在线收款退款
  • 最强的Python可视化神器,你有用过么?
  • 【DFS专题】深度优先搜索 “暴搜”优质题单推荐 10道题(C++ | 洛谷 | acwing)
  • ChatGPT 引领的 AI 革命爆发了,一起上车吧!
  • 你是真的“C”——进行动态内存分配库函数的使用详解
  • 【Java】7 再识数组|数组的基本操作
  • 【数据结构】用队列实现栈
  • 应届生投腾讯,被面试官问了8个和 ThreadLocal 相关的问题。
  • 树莓派Pico开发板I2C OLED显示模块接口与MicroPython编程
  • 联合体(共用体)
  • C bomb(tarjin + 拓扑排序)
  • 又一款全新的基于 GPT4 的 Python 神器Cursor,关键还免费
  • STM32 ADC+定时器+DMA+FFT
  • Nginx的漏洞浮现
  • 机场航拍图像检测软件(Python+YOLOv5深度学习模型+清新界面)
  • I2C协议简介 Verilog实现