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

将图片资源保存到服务器的盘符中

服务类

  • 系统盘符:file-path.disk(可能会变,配置配置文件dev中)
  • 文件根路径:file-path.root-path(可能会变,配置配置文件dev中)
  • http协议的Nginx的映射前缀:PrefixConstant.HTTP_PREFIX
package com.sky.service;

import com.sky.constant.MessageConstant;
import com.sky.constant.PrefixConstant;
import com.sky.exception.BaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class CommonService {

    @Value("${file-path.disk}")
    private String disk;

    @Value("${file-path.root-path}")
    private String rootPath;


    /**
     * 文件上传
     *
     * @param parentPath 父路径
     * @param file       文件
     */

    public String upload(String parentPath, MultipartFile file) {
        // Upload file
        String fileName = file.getOriginalFilename();
        // Get full path using system file separator
        String fullPath = disk + ":" + File.separator + rootPath + File.separator + parentPath;
        // Create the directory if it doesn't exist
        File directory = new File(fullPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        // Create the destination file
        File dest = new File(directory, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }
        // Return the file access URL
        return PrefixConstant.HTTP_PREFIX +
               fileName;
    }
}

配置文件

在这里插入图片描述

总配置文件

sky:
  jwt:
    # 设置jwt签名加密时使用的秘钥
    admin-secret-key: itcast
    # 设置jwt过期时间
    admin-ttl: 720000000
    # 设置前端传递过来的令牌名称
    admin-token-name: token
  file-path:
    disk: ${file-path.disk}
    root-path: ${file-path.root-path}

开发环境配置文件

file-path:
  disk: D
  root-path: sky_take_out

常量类

在这里插入图片描述

文件路径常量

package com.sky.constant;

public class SystemPathConstant {
   public static final String COMMON = "common";


    // 构造函数私有化
     private SystemPathConstant() {
     }
}

nginx路径映射常量

package com.sky.constant;

public class PrefixConstant {

   public static final String HTTP_PREFIX = "http://localhost/files/";


   // 构造函数私有化
    private PrefixConstant() {
    }
}

controller层

别人上传完图片之后把访问路径给别人(http的路径,不是本地路径)

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传:{}", file);
        // 将文件上传到本地文件夹下
        // 返回文件的访问路径
        String filePath = commonService.upload(SystemPathConstant.COMMON,file);
        return Result.success(filePath);
    }

配置类放行静态资源

package com.sky.config;

import com.sky.constant.SystemPathConstant;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.List;

/**
 * 配置类,注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;

    @Value("${file-path.disk}")
    private String disk;

    @Value("${file-path.root-path}")
    private String rootPath;


   ..... 其他配置一万行
    /**
     * 设置静态资源映射
     * @param registry
     */
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        // Map the file directory to a URL path
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:" +
                        disk + ":" + "/" +
                        rootPath + "/" +
                        SystemPathConstant.COMMON + "/");

    }


}

nginx映射

静态资源到本地盘符(这就你的代码中配置的判读)

  • 这个文件是开发环境的,正式环境按照正式环境的路径和盘符配置
    改完记得重启一下
       location /files/ {
            alias D:/sky_take_out/common/;
        }
  • 有的时候会访问403 异常
  • 文件权限异常
  • 访问一定要访问具体文件,不要访问到文件夹
    在这里插入图片描述

http://www.kler.cn/news/322594.html

相关文章:

  • LLaMA-Factory 使用 sharegpt 格式的数据集
  • nacos 快速入门
  • 【如何学习操作系统】——学会学习的艺术
  • 简单上手vue使用vue-plugin-hiprint进行打印
  • 【FastAPI】使用 SQLAlchemy 和 FastAPI 实现 PostgreSQL 中的 JSON 数据 CRUD 操作
  • 【线程】POSIX信号量---基于环形队列的生产消费者模型
  • windows10使用bat脚本安装前后端环境之msyql5.7安装配置并重置用户密码
  • Meta震撼发布Llama3.2大规模模型
  • 记录QTreeView使用(item勾选,事件,过滤)
  • cubemx配置ADC
  • [3]Opengl ES着色器
  • ST188单光束反射式红外光电传感器心率测量原理
  • 混拨动态IP代理的优势是什么
  • 网络编程(10)——json序列化
  • leetcode721. 账户合并
  • 高级算法设计与分析 学习笔记9 跳表
  • 【论文阅读】RISE: 3D Perception Makes Real-World Robot Imitation Simple and Effective
  • 动态规划入门题目->使用最小费用爬楼梯
  • Ceph 基本架构(一)
  • Docker实践与应用
  • QT开发模式(一):界面和业务逻辑分离
  • 基于Hive和Hadoop的电商消费分析系统
  • 人工智能之计算机视觉的发展历程与相关技术内容,相应的模型介绍
  • docker-文件复制(docker cp:用于在Docker主机和容器之间拷贝文件或目录)
  • Windows系统的Tomcat日志路径配置
  • 在 Ubuntu 上构建 Electron 项目时的问题记录和解决方法
  • Meta的LLaMA 3.2系列大模型打败OpenAI,Orion的原型AR眼镜更是引领科技新时代!
  • WiFi无线连接管理安卓设备工具:WiFiADB
  • 初学者教程:如何使用谷歌云API
  • 怎样用云手机进行TikTok矩阵运营?