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

相关推荐
用户908324602733 小时前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
用户8307196840821 天前
Spring Boot 集成 RabbitMQ :8 个最佳实践,杜绝消息丢失与队列阻塞
spring boot·后端·rabbitmq
Java水解1 天前
Spring Boot 视图层与模板引擎
spring boot·后端
Java水解1 天前
一文搞懂 Spring Boot 默认数据库连接池 HikariCP
spring boot·后端
洋洋技术笔记1 天前
Spring Boot Web MVC配置详解
spring boot·后端
初次攀爬者2 天前
Kafka 基础介绍
spring boot·kafka·消息队列
用户8307196840822 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
Java水解2 天前
SpringBoot3全栈开发实战:从入门到精通的完整指南
spring boot·后端
初次攀爬者3 天前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺3 天前
搞懂@Autowired 与@Resuorce
java·spring boot·后端