在Spring Boot中实现图片上传和修改

1. 图片上传实现步骤

1.1 添加依赖

确保 spring-boot-starter-webspring-boot-starter-validation 已存在:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
1.2 配置文件上传限制

application.properties 中配置最大文件大小:

properties 复制代码
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
1.3 编写上传接口
java 复制代码
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class ImageController {

    // 指定图片存储目录(示例路径,建议使用配置类或环境变量)
    private final String UPLOAD_DIR = "src/main/resources/static/images/";

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件不能为空";
        }

        // 生成唯一文件名(防止重复)
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + fileExtension;

        // 创建目标文件
        File dest = new File(UPLOAD_DIR + newFileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs(); // 创建目录
        }

        // 保存文件
        file.transferTo(dest);
        return "上传成功,访问地址: /images/" + newFileName;
    }
}
1.4 配置静态资源访问

默认情况下,static 目录下的文件可以直接访问。如果需要自定义路径,添加配置类:

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:src/main/resources/static/images/");
    }
}

2. 图片修改实现步骤

修改图片通常需要先删除旧图片,再上传新图片,并更新数据库记录(如果有)。

2.1 添加删除旧图片的逻辑
java 复制代码
public class ImageController {

    @PostMapping("/update")
    public String updateImage(
            @RequestParam("oldFileName") String oldFileName,
            @RequestParam("newFile") MultipartFile newFile) throws IOException {
        
        // 删除旧图片
        File oldFile = new File(UPLOAD_DIR + oldFileName);
        if (oldFile.exists()) {
            oldFile.delete();
        }

        // 上传新图片
        return uploadImage(newFile);
    }
}
2.2 结合数据库操作(示例)

如果图片路径存储在数据库中,需结合JPA/Hibernate更新记录:

java 复制代码
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String avatar; // 图片路径字段
    // getter/setter
}

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/user/{userId}/avatar")
    public String updateAvatar(
            @PathVariable Long userId,
            @RequestParam("file") MultipartFile file) throws IOException {
        
        User user = userRepository.findById(userId).orElseThrow();
        
        // 删除旧头像(如果有)
        if (user.getAvatar() != null) {
            File oldFile = new File(UPLOAD_DIR + user.getAvatar());
            if (oldFile.exists()) oldFile.delete();
        }

        // 上传新头像并更新数据库
        String newFileName = UUID.randomUUID() + getFileExtension(file);
        file.transferTo(new File(UPLOAD_DIR + newFileName));
        user.setAvatar(newFileName);
        userRepository.save(user);

        return "头像更新成功";
    }

    private String getFileExtension(MultipartFile file) {
        String name = file.getOriginalFilename();
        return name.substring(name.lastIndexOf("."));
    }
}

3. 前端调用示例(HTML)

html 复制代码
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">上传</button>
</form>

<form action="/update" method="post" enctype="multipart/form-data">
    <input type="hidden" name="oldFileName" value="old-image.jpg">
    <input type="file" name="newFile">
    <button type="submit">修改图片</button>
</form>

4. 注意事项

  1. 安全性 :限制文件类型(如仅允许 image/jpeg, image/png),避免上传恶意文件。
  2. 异常处理 :捕获 IOException 并返回友好提示。
  3. 分布式部署:若多实例部署,需使用云存储(如阿里云OSS、七牛云)替代本地存储。
  4. 路径管理 :建议将上传路径配置在 application.properties 中,避免硬编码。

通过以上步骤,即可在Spring Boot中实现图片的上传和修改功能。

相关推荐
胚芽鞘6814 小时前
关于java项目中maven的理解
java·数据库·maven
nbsaas-boot5 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
仗剑_走天涯5 小时前
基于pytorch.nn模块实现线性模型
人工智能·pytorch·python·深度学习
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
CJi0NG5 小时前
【自用】JavaSE--算法、正则表达式、异常
java
Hellyc5 小时前
用户查询优惠券之缓存击穿
java·redis·缓存
今天又在摸鱼6 小时前
Maven
java·maven
老马啸西风6 小时前
maven 发布到中央仓库常用脚本-02
java·maven
代码的余温6 小时前
MyBatis集成Logback日志全攻略
java·tomcat·mybatis·logback