zoukankan      html  css  js  c++  java
  • SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url

    场景

    前端调用上传照片的功能,将某照片上传到服务器上某磁盘路径下,然后将通过静态资源映射,将在服务器上

    访问的地址存储到数据库中,这样在需要获取这种照片的时候就能通过服务器上的url来获取和显示这张照片。

    若依前后端分离版本地搭建开发环境并运行项目的教程:

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662

    在此基础上搭建起来前后端分离的项目,然后使用若依的通用的上传接口实现图片的上传。

    关于图片的上传的前端以及全流程可以参照:

    SpringBoot+El-upload实现上传文件到通用上传接口并返回文件全路径(若依前后端分离版源码分析):

    https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108383134

    这里重点讲后台的配置。

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    首先图片上传的通用接口,首先新建通用上传文件的接口

    /**
     * 通用文件上传下载接口
     * @author
     */
    @RestController
    @RequestMapping("file")
    @Api(tags = "文件通用上传下载")
    public class FileController {
    
        @Autowired
        private FilePathProperties filePathProperties;
    
        /**
         * 上传文件
         *
         * @param file
         * @return
         */
        @PreAuthorize(hasPermi = "system:file:upload")
        @PostMapping("upload")
        @ApiOperation("上传")
        public AjaxResult uploadFile(@Param("file") MultipartFile file) {
            AjaxResult ajaxResult = AjaxResult.success();
            try {
                // 显示头像文件夹路径
                String path = filePathProperties.getPath() + "/" + DateUtils.datePath() + "/";
                FileUtils.check_folder(path);
                // 上传后的文件名称
                String auth_file_name = UploadUtil.save_file(file, path);
                if (StringUtils.isEmpty(auth_file_name)){
                    return AjaxResult.error(HttpStatus.BAD_REQUEST, "文件格式不合法");
                }
                ajaxResult.put("code", 200);
                ajaxResult.put("message", "成功");
                ajaxResult.put("fileName", path + auth_file_name);
            } catch (IOException e) {
                ajaxResult.put("code", 400);
                ajaxResult.put("message", "上传失败");
                e.printStackTrace();
            }
            return ajaxResult;
        }
    
        /**
         * 下载文件
         * @param fileName
         * @param response
         * @throws IOException
         */
        @GetMapping("download")
        @ApiOperation("下载")
        public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
            File file = new File(fileName);
            // 清空response
            response.reset();
            // 设置response的Header 通知浏览器 已下载的方式打开文件 防止文本图片预览
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1")); // 转码之后下载的文件不会出现中文乱码
            response.addHeader("Content-Length", "" + file.length());
            // 以流的形式下载文件
            InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }
    }

    然后这里的filePathProperties是读取配置文件中配置的文件上传路径

    然后需要在代码中添加读取配置文件的配置类

    /**
     * 读取服务器上传文件磁盘路径
     */
    @Configuration
    @RefreshScope
    @ConfigurationProperties(prefix = "file")
    public class FilePathProperties {
        /**
         * 传文件磁盘路径
         */
        private String path;
    
        public String getPath()
        {
            return path;
        }
    
        public void setPath(String path)
        {
            this.path = path;
        }
    }

    然后前端调用上传文件接口,并且将照片上传到服务器上指定的路径下,再调用保存接口时将通用上传接口返回的文件路径作为保存接口的参数

    然后照片就会上传到服务器上指定的路径

    然后就是添加静态资源映射的配置类

    package com.ruoyi.fzys.config;
    
    import com.ruoyi.common.core.constant.Constants;
    import com.ruoyi.fzys.config.properties.FilePathProperties;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import java.io.File;
    
    
    /**
     * 通用配置
     *
     * @author ruoyi
     */
    @Configuration
    public class ResourcesConfig implements WebMvcConfigurer
    {
    
        @Autowired
        private FilePathProperties filePathProperties;
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry)
        {
            /** 本地文件上传路径 */
            registry.addResourceHandler(Constants.RESOURCE_PREFIX_DEFINED+"/**").addResourceLocations("file:" + filePathProperties.getPath() + File.separator);
    
        }
    
        /**
         * 自定义拦截规则
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry)
        {
    
        }
    }

    这里实现WebMvcConfigurer的addResourceHandlers方法

    主要是通过下面实现静态资源映射

    registry.addResourceHandler(Constants.RESOURCE_PREFIX_DEFINED+"/**").addResourceLocations("file:" + filePathProperties.getPath() + File.separator);

    前面是请求资源的路径,后面是磁盘中的实际路径。

    为了使请求资源的路径的前缀一致,将其配置得全局常量类中

        /**
         * 资源映射路径 前缀  自定义
         */
        public static final String RESOURCE_PREFIX_DEFINED = "/file";

    然后在将图片路径保存到数据的接口中

        public AjaxResult add(@RequestBody BusPhotoManagement busPhotoManagement, HttpServletRequest request)
        {
            String filePath = filePathProperties.getPath();
            String path=busPhotoManagement.getPhotoPath().substring(filePath.length());
            //获取协议号
            String localAddr = request.getLocalAddr();
            int localPort = request.getLocalPort();
            String finalURL= Constants.HTTP +localAddr+":"+localPort+Constants.RESOURCE_PREFIX_DEFINED+path;
            System.out.println("最终路径 finalURL:"+finalURL);
            busPhotoManagement.setPhotoPath(finalURL);
            return toAjax(busPhotoManagementService.insertBusPhotoManagement(busPhotoManagement));
        }

    其中filePathProperties和上面使用的配置文件路径的一样

    busPhotoManagement.getPhotoPath().substring(filePath.length());就是上面调用通用上传接口返回的实际的磁盘路径

    Constants.HTTP 是全局常量

        /**
         * http请求
         */
        public static final String HTTP = "http://";

    然后最终将finalURL存储到数据库中就是该照片的网络url

    能直接在浏览器中访问

    博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
  • 相关阅读:
    Unity 5.3 Assetbundle热更资源
    自定义协同程序:CustomYieldInstruction
    C# 温故而知新: 线程篇(四)
    C# 温故而知新: 线程篇(三)
    C# 温故而知新: 线程篇(二)
    c# 温故而知新: 线程篇(一)
    C# 温故而知新:Stream篇(六)
    C# 温故而知新:Stream篇(七)
    C# 温故而知新:Stream篇(四)
    Redis高级数据类型
  • 原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/14623311.html
Copyright © 2011-2022 走看看