本地图片的保存以及访问

上传多张图片并压缩生成新的图片接口实现

java 复制代码
@Api(tags = "图片上传")
@RestController
@RequestMapping("/admin/system/mage")
public class MageController {


/*    @Value("${bendi.oss.log}")
    private String baseUrl;*/
    @Value("${file.uploadFolder}")
    private String filepath;
    @Value("${file.pathPattern}")
    private String pathPattern;
    @Value("${file.basePath}")
    private String basePath;


    @PostMapping("/uploads")
    public Result<List<Mage>> upload(List<MultipartFile> files, HttpServletRequest request){
        List<Mage> fileNamess = new ArrayList<>();
        Mage mage = new Mage();
        for (MultipartFile file : files) {
            // 拿到文件名
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
            //使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            try {
                String path = filepath+"file_image";
                File fileDir = new File(path);
                if(!fileDir.exists()){
                    // 递归生成文件夹
                    fileDir.mkdirs();
                }
                File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileName);
                file.transferTo(newFile);
                long maxSize = 5 * 1024 * 1024;
                if(file.getSize() > maxSize){
                    // 复制一份原始图片文件
                    File copyFile = new File(fileDir.getAbsolutePath() + File.separator + "S"+fileName);
                    Files.copy(newFile.toPath(), copyFile.toPath());
                    Thumbnails.of(copyFile)
                            .scale(1f)
                            .outputQuality(0.7f)
                            .toFile(copyFile);
                     mage.setActivityPhoto(basePath + newFile.getAbsolutePath().replace("\\", "/").replace(basePath, "#").split("#")[1]);
                     mage.setActivityPhotoThumbnail(basePath + copyFile.getAbsolutePath().replace("\\", "/").replace(basePath, "#").split("#")[1]);
                    fileNamess.add(mage);
                }else {
                    mage.setActivityPhoto(basePath + newFile.getAbsolutePath().replace("\\", "/").replace(basePath, "#").split("#")[1]);
                    mage.setActivityPhotoThumbnail(basePath + newFile.getAbsolutePath().replace("\\", "/").replace(basePath, "#").split("#")[1]);
                    fileNamess.add(mage);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println(fileNamess+"zzz");
        return Result.ok(fileNamess);
    }

配置存储地址:

yml 复制代码
file:
  uploadFolder: D:/upload/hanghai/
  staticAccessPath: /hanghai/**
  basePath: /hanghai/
  uploadPath: D:/upload/hanghai/file_image
  pathPatterns: /uploads/**
  pathPattern: /uploads/

添加静态资源处理

java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
    }
}

补充知识:

复制代码
WebMvcConfigurer 是 Spring Boot Web 模块中一个重要的接口,它提供了一系列方法来配置 Spring MVC 的相关设置。通过实现这个接口,可以自定义一些 Web MVC 的配置,例如视图解析器、静态资源处理、拦截器等。

WebMvcConfigurer 接口中定义了以下方法:

addViewHandlers(List<ViewHandler> viewHandlers):添加视图处理器。
addResourceHandlers(ResourceHandlerRegistry registry):添加静态资源处理器。
addInterceptors(InterceptorRegistry registry):添加拦截器。
addViewController(String path, ViewController viewController):添加视图控制器。
addViewResolvers(List<ViewResolver> viewResolvers):添加视图解析器。
configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer):配置默认 Servlet 处理器。
configurePathMatch(PathMatchConfigurer configurer):配置路径匹配。
configureContentNegotiation(ContentNegotiationConfigurer configurer):配置内容协商。
configureAsyncSupport(AsyncSupportConfigurer configurer):配置异步支持。
configureUriCompatibility(UriCompatibilityConfigurer configurer):配置 URI 兼容性。
configureHttpMessageConverters(HttpMessageConverter<?>... converters):配置 HTTP 消息转换器。
configureWebMvc(WebMvcConfigurer configurer):配置 Web MVC。
这些方法可以用来定制 Spring MVC 的各种功能,使得 Spring Boot 项目更加灵活和可扩展。

在使用 WebMvcConfigurer 时,需要注意以下几点:

如果需要自定义视图解析器,需要实现 ViewResolver 接口,并将其添加到 addViewResolvers 方法中。
如果需要自定义静态资源处理器,需要实现 ResourceHandler 接口,并将其添加到 addResourceHandlers 方法中。
如果需要自定义拦截器,需要实现 Interceptor 接口,并将其添加到 addInterceptors 方法中。
如果需要自定义视图控制器,需要实现 ViewController 接口,并将其添加到 addViewController 方法中。
总之,WebMvcConfigurer 是 Spring Boot Web 模块中非常重要的一部分,通过实现这个接口,可以灵活地配置 Spring MVC,使得项目更加符合实际需求。
相关推荐
朝新_1 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir1 小时前
Calendar类日期设置进位问题
java·开发语言
季鸢3 小时前
Java设计模式之状态模式详解
java·设计模式·状态模式
@yanyu6663 小时前
springboot实现查询学生
java·spring boot·后端
ascarl20104 小时前
准确--k8s cgroup问题排查
java·开发语言
magic 2454 小时前
Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误
java
爱敲代码的憨仔4 小时前
分布式协同自动化办公系统-工作流引擎-流程设计
java·flowable·oa
纪元A梦4 小时前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
卿着飞翔4 小时前
RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)
java·rabbitmq·java-rabbitmq
陈阿土i4 小时前
SpringAI 1.0.0 正式版——利用Redis存储会话(ChatMemory)
java·redis·ai·springai