springboot上传图片到本地
简介:本文讲解,如何使用springboot,将代码上传到本地的某个特定的文件夹。
项目的演示文件,在这个地址:https://gitee.com/geek-li-hua/code-in-blog.git
- 项目结构
数据库设计
DROP TABLE IF EXISTS `url_database`; CREATE TABLE `url_database` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '图片id', `url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '图片的url', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
application.properties
server.port = 8080 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.15</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>ImageUploadLocally-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ImageUploadLocally-demo</name> <description>ImageUploadLocally-demo</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Spring Boot Starter JDBC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- Project Lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <!-- MySQL Connector/J --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.32</version> </dependency> <!-- MyBatis Plus Boot Starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.2</version> </dependency> <!-- MyBatis Plus Generator --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
关键方法
这个方法就是,上传文件的核心代码。
/** * 上传文件方法 * * @param file 要上传的文件 * @return 返回上传结果 */ public String upload(MultipartFile file) { if (file.isEmpty()) { return "No file uploaded"; // 如果文件为空,则返回提示信息"未上传文件" } String originalFilename = file.getOriginalFilename(); // 获取原始文件名 String ext='.' + originalFilename.split("\\.")[1]; // 获取文件扩展名 String uuid = UUID.randomUUID().toString().replace("-", ""); // 生成随机UUID String newFileName = uuid + ext; // 新文件名 // 上传图片 ApplicationHome applicationHome = new ApplicationHome(this.getClass()); // 获取应用程序的根目录 String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\"; // 设置图片存储路径 String path = pre + newFileName; // 图片完整路径 try{ file.transferTo(new File(path)); // 将文件保存到指定路径 } catch (IOException e){ e.printStackTrace(); // 打印异常信息 } return path; // 返回上传成功信息 }
然后就是再这个基础上封装一下返回结果,和对于数据库的CRUD。
于是有了下面的代码
/** * <p> * 前端控制器 * </p> * * @author jakelihua * @since 2023-09-10 */ @Controller @RequestMapping("/url-database") public class UrlDatabaseController { /** * 上传文件方法 * * @param file 要上传的文件 * @return 返回上传结果 */ @Autowired private IUrlDatabaseService urlDatabaseService; @PostMapping("/upload") public Result addFile(MultipartFile file) { String path = upload(file); if (path.equals("No file uploaded")) { return Result.fail("No file uploaded"); } System.out.println(path); if (urlDatabaseService.save(new UrlDatabase(path))){ return Result.success(path); } else { return Result.fail("save fail"); } } public String upload(MultipartFile file) { if (file.isEmpty()) { return "No file uploaded"; // 如果文件为空,则返回提示信息"未上传文件" } String originalFilename = file.getOriginalFilename(); // 获取原始文件名 String ext='.' + originalFilename.split("\\.")[1]; // 获取文件扩展名 String uuid = UUID.randomUUID().toString().replace("-", ""); // 生成随机UUID String newFileName = uuid + ext; // 新文件名 // 上传图片 ApplicationHome applicationHome = new ApplicationHome(this.getClass()); // 获取应用程序的根目录 String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\"; // 设置图片存储路径 String path = pre + newFileName; // 图片完整路径 try{ file.transferTo(new File(path)); // 将文件保存到指定路径 } catch (IOException e){ e.printStackTrace(); // 打印异常信息 } return path; // 返回上传成功信息 } // 路由器首页 @RequestMapping("/") public String index(){ return "index.html"; } }
添加成功的标致。
- 前端测试代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传图片</title> </head> <body> <form action="/url-database/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" value="上传图片"> <input type="submit" value="上传"> </form> </body> </html>