记录解决springboot项目上传图片到本地,在html里不能回显的问题

项目场景:

项目场景:在我的博客系统里:有个相册模块:需要把图片上传到项目里,在html页面上显示


解决方案

1.建一个文件夹

例如在windows系统下。可以在项目根目录下建个photos文件夹,把上传的图片文件保存到这个文件夹里

2.实现WebMvcConfigurer

重写addResourceHandlers方法

java 复制代码
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Value("${uploadLinuxTempFilePath}")
    private String linuxUploadPath;



    /**
     * 解决上传图片后不能立即访问到(回显)的问题
     * */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // http://localhost//upload_img/photos/1720864412594.png
        // 访问上传到本地的图片
        String path;
        String os = System.getProperty("os.name");
        if(os.startsWith("Windows")){
            path = System.getProperty("user.dir")+"/photos/";
        }else {
            path = linuxUploadPath;
        }
        // 例如访问http://111.229.128.4:80//upload_img/1720877954983.jpg
        // 只要匹配到/upload_img/路径,springmvc会自动映射到你建的 path  路径下
        registry.addResourceHandler("/upload_img/**")
                .addResourceLocations("file:"+path);
    }

3.保存到表里的文件路径

我这个是保存到linux上,所以ip是我的服务器ip

如果是上传到你的windows电脑上, ip就是127.0.0.1

4.附上传图片的代码

java 复制代码
package com.lizhenqiang.myblog.util;

import lombok.extern.slf4j.Slf4j;
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.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class UploadFileUtil {
    @Value("${uploadLinuxTempFilePath}")
    private String linuxUploadPath;


    @Value("${server.port}")
    private int port;

    @Value("${linuxIP}")
    private String linuxIp;

    public String uploadFileToLocal(MultipartFile file) {
        // [1] 获取项目目录
        // http://localhost//upload_img/1720864412594.png
        log.info("[开始] 拼接保存到本地的完整文件路径");
        String userDir = System.getProperty("user.dir");

        // [2] 在项目目录下新建一个文件夹
        String targetDir = "/photos/";

        // [3] 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String[] split = originalFilename.split("\\.");
        String suffix = split[1];

        // [4] 组装完整文件路径
        String fileName =  System.currentTimeMillis()+ "." +suffix;
        String filePath;

        String prefixIp;
        String os = System.getProperty("os.name");

        if(os.startsWith("Windows")){
            filePath = userDir + targetDir + fileName;
            prefixIp = "http://127.0.0.1:"+port+"//upload_img/";
        }else {
            filePath = linuxUploadPath + fileName ;
            prefixIp = "http://"+linuxIp+":"+port+"//upload_img/";
        }


        // [4.1] 判断路径是否存在, 如果不存在则创建
        this.createDirectoryIfNotExits(filePath);
        log.info("[结束] 拼接保存到本地的完整文件路径, 文件路径 [{}]", filePath);


        // [5] 获取输入流、创建输出流
        log.info("[开始] 复制文件到本地, 文件路径 [{}]", filePath);
        try (InputStream inputStream = file.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(filePath)) {
            // [6] 从输入流读, 往输出流写
            int readBytes;
            byte[] bytes = new byte[1024];
            while ((readBytes = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, readBytes);
            }

            // [7] 刷新输出流
            outputStream.flush();
            log.info("[结束] 复制文件到本地, 文件路径 [{}]", filePath);

            // [8] 返回文件完整路径
            return prefixIp+ fileName;


        } catch (IOException e) {
            log.info("[失败] 复制文件到本地, 文件路径 [{}], 异常信息 [{}]", filePath, e.getMessage());
            throw new RuntimeException("复制文件到本地失败");
        }
    }


    /**
     * 判断文件路径是否存在, 不存在则创建
     *
     * @param path 文件完整路径
     */
    public void createDirectoryIfNotExits(String path) {
        /*
         逻辑:
         1. 判断是否是文件夹, 如果是文件夹, 在判断文件夹是否存在, 不存在则创建
         2. 如果不是文件夹, 就获取它的目录, 不存在则创建
         */


        // [1] 判断是否是文件夹, 如果是文件夹, 在判断文件夹是否存在, 不存在则创建
        File file = new File(path);
        if (file.isDirectory()) {
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            // [2] 如果不是文件夹, 就获取它的目录, 不存在则创建
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
        }
    }

}

5.欢迎访问我的博客系统

基于Java(Springboot)可以用做毕业设计的个人博客系统,包括网站前台和后台管理系统两部分。网站前台包括首页、归档页面、相册页面、留言页面、关于我页面。支持用户注册与登录,注册时使用邮箱发送验证码。

后台管理系统包括写博客、管理博客。对分类、标签、相册、用户的增删改查。还有对访客的记录。

网站链接 前台: http://111.229.128.4/

后台: http://111.229.128.4/admin

用户名/密码:admin/admin

前端框架:Layui

后端:Springboot

数据库:MySQL,redis

欢迎访问!

相关推荐
RuoyiOffice6 分钟前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
xmjd msup34 分钟前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
Vane137 分钟前
从零开发一个AI插件,经历了什么?
人工智能·后端
952361 小时前
SpringBoot统一功能处理
java·spring boot·后端
rleS IONS1 小时前
SpringBoot中自定义Starter
java·spring boot·后端
DevilSeagull2 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务
TeDi TIVE3 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
雨辰AI3 小时前
SpringBoot3 + 人大金仓 V9 微服务监控实战|Prometheus+Grafana+SkyWalking 全链路监控
数据库·后端·微服务·grafana·prometheus·skywalking
二哈赛车手3 小时前
新人笔记---ES和kibana启动问题以及一些常用的linux的错误排查方法,以及ES,数据库泄密解决方案[超详细]
java·linux·数据库·spring boot·笔记·elasticsearch
Nicander3 小时前
理解 mybatis 源码:vibe-coding一个mini-mybatis
后端·mybatis