栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 整合文件上传 elment Ui 上传组件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 整合文件上传 elment Ui 上传组件

SpringBoot 整合文件上传 elment Ui 上传组件

本文章记录 自己学习使用 侵权必删!

前端代码

博主最近在学 elment Ui 所以 前端使用 elmentUi 的 upload 组件实现

  • 因为 elmentui 是基于 vue 的环境 使用的 所以我们 得引用 vue 的 js 文件
引入 elmentUi 的 css 和 js

我们采用官网的这种 cdn 的方式

  • 本地的引入的方式 容易导致elementUI与 vue 版本不匹配
  • 出现Vue warn]: Injection “elForm” not found报错解决方法






项目的目录结构:

搭建前端页面

页面效果

光光这些肯定不够 我们还需要前后端交互的页面

  • 创建的文件名称:index.html

  • 文件位置: /resources/static/index.html



  
    
    测试文件上传
    
    
    
    
    
    
  
  
    

所使用的依赖

找到 pom.xml

  • 因为只用到了接口 我们导入 web 的依赖即可

        spring-boot-starter-parent
        org.springframework.boot
        2.5.0
    

    
        8
        8
        UTF-8
    
	
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    
后端代码 controller
@RestController
public class FileController {

    
    @Configuration
    public static class MyPicConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/img
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile urlFile,HttpServletRequest request) {
        //  url =》 http://localhost:8899/upload
        StringBuffer url = request.getRequestURL();
        // 意思是 取出ip地址加端口 http://localhost:8899
        String baseUrl = url.substring(0, url.length() - (url.length() - url.lastIndexOf("/")));
        // 文件名称
        String fileName = System.currentTimeMillis() + urlFile.getOriginalFilename();
        // 文件存储的路径
        String filePath = System.getProperty("user.dir") + "\src\main\resources\static\img\";
        File file = new File(filePath);
        // 当文件夹不存在 创建文件夹
        if (!file.exists()) {
            file.mkdir();
        }
        File dest = new File(filePath + fileName);
        String storeUrlPath = "/img/" + fileName;

        try {
            // 写到文件夹中
            urlFile.transferTo(dest);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            throw new RuntimeException(e);
        }
        return baseUrl+storeUrlPath;
    }

}
解析代码

我们现在接收上传文件的接口 打上断点 下面一步一步解析里面的代码

  • request.getRequestURL() 意思是 获取当前请求的地址
  • http://localhost:8899/upload 是这种格式
  • baseUrl: 是截取到http://localhost:8899这串字符
  • 在返回到前端页面展示的时候需要用到
  • fileName

  • System.getProperty(“user.dir”) 获取的时候 当前项目在磁盘的路径

这样就上传成功啦 那么 我们该如何去访问这个图片呢?

来到这里 当我们访问的资源文件路径为/img开头的时候 会默认 去到"file:"+System.getProperty(“user.dir”) + "srcmainresourcesstaticimg"来寻找 就是我们项目的静态资源文件夹的位置

  • 这个位置可以是任意位置

页面效果

可以看到 当我们 上传成功后 资源成功的展示到了 我们的页面上

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000265.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号