项目1总结其三(图片上传功能)

1、UploadService

java 复制代码
public interface UploadService {
    //上传图片
    String uploadImage(MultipartFile file, String type);
}

upload.location = D:/upload

java 复制代码
@Value("${upload.location}")
    private String uploadLocation;//文件上传路径

    @Override
    public String uploadImage(MultipartFile file, String type) {
        //1.创建目录
        File dir = new File(uploadLocation + "/images/" + type);
        if (!dir.exists()) {
            boolean b = dir.mkdirs();//级联创建目录
            if (!b) {
                throw new F1Exception("级联创建目录异常");
            }
        }
        //2.给上传的文件起名
        LocalDateTime now = LocalDateTime.now();
        String fileName = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Random random = new Random();
        int sid = random.nextInt(1000);//0~999
        fileName = fileName + "-" + sid;

        //3.拼扩展名
        String originalFileName = file.getOriginalFilename();//上传文件名
        //assert originalFileName != null;
        int idx = originalFileName.lastIndexOf(".");
        String ext = originalFileName.substring(idx);
        fileName = fileName + ext;

        //完整的文件名
        String fullName = dir.getAbsolutePath() + "/" + fileName;

        //要存储的目标文件
        File target = new File(fullName);

        //4.存储文件
        try {
            file.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException("保存文件失败");
        }

        //5.返回访问地址和存储地址
        return "/images/" + type + "/" + fileName;
    }


修正:图片中的回显操作并非通过interceptor,而是通过资源定位实现的

后记:这里的D:/upload完全可以用@Value注入

思路就是:

通过组件的action操作---后端api调用service操作---保存文件---前端回显访问baseUrl + /image/xxx这个链接 --- 后端通过资源定位,将该链接定位到存放资源的位置

相关推荐
Lhan.zzZ1 小时前
笔记_2026.4.28_004
c++·ide·笔记·qt
callJJ4 小时前
Spring Data Redis 两种编程模型详解:同步 vs 响应式
java·spring boot·redis·python·spring
海兰4 小时前
【第27篇】Micrometer + Zipkin
人工智能·spring boot·alibaba·spring ai
海兰6 小时前
【第28篇】可观测性实战:LangFuse 方案详解
人工智能·spring boot·alibaba·spring ai
RuoyiOffice6 小时前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
xmjd msup7 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
952367 小时前
SpringBoot统一功能处理
java·spring boot·后端
rleS IONS7 小时前
SpringBoot中自定义Starter
java·spring boot·后端
TeDi TIVE9 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
二哈赛车手9 小时前
新人笔记---ES和kibana启动问题以及一些常用的linux的错误排查方法,以及ES,数据库泄密解决方案[超详细]
java·linux·数据库·spring boot·笔记·elasticsearch