项目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这个链接 --- 后端通过资源定位,将该链接定位到存放资源的位置

相关推荐
全职计算机毕业设计1 天前
基于SpringBoot框架的在线教育系统设计与实现(三套文档参考)
java·spring boot·后端
No8g攻城狮1 天前
【异常解决】使用DateUtil.isSameDay()方法判断秒级时间戳是否属于同一天踩过的坑
java·jvm·spring boot·java-ee·springboot
努力也学不会java1 天前
【Spring】Spring事务和事务传播机制
java·开发语言·人工智能·spring boot·后端·spring
IT·陈寒1 天前
从 Spring 到 SpringBoot,再到 SpringAI:框架的进化与思考
java·spring boot·spring
MeowKnight9581 天前
vscode安装、部署和小技巧 记录
ide·vscode·编辑器
ZeroMxy1 天前
VSCode 修改默认主题
ide·vscode·编辑器
张较瘦_1 天前
Springboot | 初识Springboot 从“手动做饭”到“点外卖”的编程革命
java·spring boot·后端
一个龙的传说1 天前
springboot优雅停止的流程梳理
java·spring boot·rpc
摇滚侠1 天前
Spring Boot 3零基础教程,WEB 开发 国际化 Spring Boot + Thymeleaf 笔记45
spring boot·笔记·后端
生莫甲鲁浪戴1 天前
Android Studio新手开发第二十八天
android·ide·android studio