ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url

2021-04-06 19:34:48  阅读:190  来源: 互联网

标签:SpringBoot Url 路径 file WebMvcConfigurer path 上传 public String


场景

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

访问的地址存储到数据库中,这样在需要获取这种照片的时候就能通过服务器上的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

能直接在浏览器中访问

 

 

标签:SpringBoot,Url,路径,file,WebMvcConfigurer,path,上传,public,String
来源: https://www.cnblogs.com/badaoliumangqizhi/p/14623311.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有