前言:
在小型demo项目中,一般将图片音频等字节流文件存放本地数据库,但企业级项目中,由于数据量容量有限,需要借助OSS来管理大规模文件。
OSS(对象存储服务,Object Storage Service)是一种用于存储和管理非结构化数据的云存储服务,适合存储图片、视频、文档等大规模数据。它具有高扩展性、高可靠性、低成本和易用性等特点,广泛应用于数据备份、多媒体存储、大数据分析和静态网站托管等场景。使用OSS的基本流程包括:首先在云服务提供商平台创建存储空间(Bucket),然后通过API、SDK或管理控制台上传和管理文件,设置访问权限以确保数据安全,最后可以通过生成的(临时)URL访问存储的文件。
本章在讲解如何使用mysql存储字节型数据后,示范如何使用阿里云OSS服务完成文件的存取,并提供对应前端代码而非postman调用接口。
本章项目源码如下:(注意将application中内容换成3.6部分内容)
wlf728050719/SpringCloudPro3-1https://github.com/wlf728050719/SpringCloudPro3-1 以及本专栏会持续更新微服务项目,每一章的项目都会基于前一章项目进行功能的完善,欢迎小伙伴们关注!同时如果只是对单章感兴趣也不用从头看,只需下载前一章项目即可,每一章都会有前置项目准备部分,跟着操作就能实现上一章的最终效果,当然如果是一直跟着做可以直接跳过这一部分。专栏目录链接如下,其中Base篇为基础微服务搭建,Pro篇为复杂模块实现。
从零搭建微服务项目(全)-CSDN博客https://blog.csdn.net/wlf2030/article/details/145799620
一、基本项目创建
1.创建Spring Boot项目,选择不添加依赖和插件
2.删除不必要目录和文件,创建application.yml
3.替换pom内容如下:
<?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.3.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.bit</groupId>
<artifactId>Pro3_1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Pro3_1</name>
<description>Pro3_1</description>
<dependencies>
<!-- Web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- Mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
<version>1.18.36</version>
<optional>true</optional>
</dependency>
<!-- test -->
<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>
4.创建存放图片的数据库和表
表sql如下:
create table tb_img
(
id int auto_increment
primary key,
name varchar(100) not null,
image longblob not null
);
yml内容如下:(替换为自己的数据库)
server:
port: 1234
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_image?useSSL=false
username: root
password: 15947035212
driver-class-name: com.mysql.jdbc.Driver
application:
name: image-service
mybatis-plus:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: cn.bit.pro3_1.mapper
5.配置数据源
二、本地数据库存取文件
1.连接成功后选择Mybatis X Generator自动生成实体类等对应代码。
2.最后生成目录如下:
3.生成mapper上加@Mapper
4.service接口加两个方法
package cn.bit.pro3_1.service;
import cn.bit.pro3_1.entity.Image;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author wlf
* @description 针对表【tb_img】的数据库操作Service
* @createDate 2025-03-10 16:39:32
*/
public interface ImageService extends IService<Image> {
int insertImage(Image image);
Image selectImageById(int id);
}
5.对应实现
package cn.bit.pro3_1.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.bit.pro3_1.entity.Image;
import cn.bit.pro3_1.service.ImageService;
import cn.bit.pro3_1.mapper.ImageMapper;
import org.springframework.stereotype.Service;
/**
* @author wlf
* @description 针对表【tb_img】的数据库操作Service实现
* @createDate 2025-03-10 16:39:32
*/
@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image>
implements ImageService{
@Override
public int insertImage(Image image) {
return baseMapper.insert(image);
}
@Override
public Image selectImageById(int id) {
return baseMapper.selectById(id);
}
}
6.创建controller包以及ImageController @CrossOrigin必须,否则出现跨域问题导致尽管业务没问题,但响应被浏览器视为错误。
package cn.bit.pro3_1.controller;
import cn.bit.pro3_1.entity.Image;
import cn.bit.pro3_1.service.ImageService;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/image")
@AllArgsConstructor
@CrossOrigin(origins = "*")
public class ImageController {
private final ImageService imageService;
/**
* 上传图片并存储到数据库
*
* @param file 前端上传的图片文件
* @return 图片的 ID
*/
@PostMapping("/upload")
public ResponseEntity<Integer> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
// 将 MultipartFile 转换为 byte[]
byte[] imageData = file.getBytes();
// 获取文件名
String fileName = file.getOriginalFilename();
// 创建 Image 对象
Image image = new Image();
image.setName(fileName);
image.setImage(imageData);
// 调用 Service 层方法存储图片
imageService.insertImage(image);
// 返回图片的 ID
return ResponseEntity.ok(image.getId());
}
/**
* 根据图片 ID 获取图片并返回给前端
*
* @param id 图片的 ID
* @return 图片的字节数据
*/
@GetMapping(value = "/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable int id) {
// 调用 Service 层方法获取图片
Image image = imageService.selectImageById(id);
if (image == null) {
return ResponseEntity.notFound().build();
}
// 返回图片的字节数据
return ResponseEntity.ok(image.getImage());
}
}
7.前端html如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload and Display</title>
</head>
<body>
<h1>Upload Image to Local Server</h1>
<form id="uploadForm">
<input type="file" id="fileInput" name="file" accept="image/*" required>
<button type="submit">Upload to Local</button>
</form>
<h1>Upload Image to AliYun OSS</h1>
<form id="aliyunUploadForm">
<input type="file" id="aliyunFileInput" name="file" accept="image/*" required>
<button type="submit">Upload to AliYun OSS</button>
</form>
<h1>Download Image from AliYun OSS</h1>
<form id="aliyunDownloadForm">
<input type="text" id="fileNameInput" placeholder="Enter file name" required>
<button type="submit">Download from AliYun OSS</button>
</form>
<h1>Display Image</h1>
<div id="imageContainer">
<!-- 图片将显示在这里 -->
</div>
<script>
// 处理本地服务器上传表单提交
document.getElementById('uploadForm').addEventListener('submit', async (event) => {
event.preventDefault();
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file.');
return;
}
const formData = new FormData();
formData.append('file', file);
try {
// 发送上传请求到本地服务器
const response = await fetch('http://localhost:1234/image/upload', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Upload failed');
}
const imageId = await response.json();
alert(`Image uploaded successfully! Image ID: ${imageId}`);
// 上传成功后显示图片
displayImage(imageId);
} catch (error) {
console.error('Error:', error);
alert('Failed to upload image.');
}
});
// 显示本地服务器图片
async function displayImage(imageId) {
try {
const response = await fetch(`http://localhost:1234/image/${imageId}`);
if (!response.ok) {
throw new Error('Failed to fetch image');
}
const imageBlob = await response.blob();
const imageUrl = URL.createObjectURL(imageBlob);
const imageContainer = document.getElementById('imageContainer');
imageContainer.innerHTML = `<img src="${imageUrl}" alt="Uploaded Image" style="max-width: 100%;">`;
} catch (error) {
console.error('Error:', error);
alert('Failed to display image.');
}
}
document.getElementById('aliyunUploadForm').addEventListener('submit', async (event) => {
event.preventDefault();
const fileInput = document.getElementById('aliyunFileInput');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file.');
return;
}
const formData = new FormData();
formData.append('file', file);
try {
// 发送上传请求到阿里云 OSS
const response = await fetch('http://localhost:1234/image/AliYunImgUpload', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Upload to AliYun OSS failed');
}
const fileName = await response.text();
alert(`Image uploaded to AliYun OSS successfully! File Name: ${fileName}`);
} catch (error) {
console.error('Error:', error);
alert('Failed to upload image to AliYun OSS.');
}
});
// 处理阿里云 OSS 下载表单提交
document.getElementById('aliyunDownloadForm').addEventListener('submit', async (event) => {
event.preventDefault();
const fileNameInput = document.getElementById('fileNameInput');
const fileName = fileNameInput.value;
if (!fileName) {
alert('Please enter a file name.');
return;
}
try {
// 发送下载请求到阿里云 OSS
const response = await fetch(`http://localhost:1234/image/AliYunImgDownload?fileName=${fileName}`);
if (!response.ok) {
throw new Error('Failed to fetch image');
}
const imageUrl = await response.text();
alert(`Image downloaded from AliYun OSS successfully! Image URL: ${imageUrl}`);
// 显示图片
displayImageFromUrl(imageUrl);
} catch (error) {
console.error('Error:', error);
alert('Failed to download image from AliYun OSS.');
}
});
// 显示阿里云 OSS 图片
function displayImageFromUrl(imageUrl) {
const imageContainer = document.getElementById('imageContainer');
imageContainer.innerHTML = `<img src="${imageUrl}" alt="Uploaded Image" style="max-width: 100%;">`;
}
</script>
</body>
</html>
8.启动服务
9.前端选择本地图片并上传
10.弹窗提示上传成功,且会马上调用一次回显从数据库取出图片
11.数据库数据成功添加。
三、OSS存取文件
1.阿里云注册账号
2025主会场_智惠采购季 就上阿里云-阿里云采购季https://www.aliyun.com/activity/purchase/purchasing?utm_content=se_10204504842.注册并登录后,搜索ram并创建用户
记得存下id和key,关闭页面后就复制不了了
3.创建后授权
4.购买oss服务,并创建bucket,使用默认的选择即可
创建后点击查看概览
记住红框里面的endpoint值
5.pom添加阿里云oss依赖
<!-- 阿里云对象存储 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
6.修改application.yml内容:(记得替换为自己的数据)
server:
port: 1234
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_image?useSSL=false
username: root
password: 15947035212
driver-class-name: com.mysql.jdbc.Driver
application:
name: image-service
cloud:
alicloud:
access-key: 你的key id
secret-key: 你的key secret
oss:
endpoint: 你的end point
bucket:
name: 你的bucket名
mybatis-plus:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: cn.bit.pro3_1.mapper
7.创建FileController
package cn.bit.pro3_1.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.net.URL;
import java.util.Date;
@RestController
@CrossOrigin(origins = "*")
public class FileController {
@Autowired
private OSS ossClient;
@Value("${spring.cloud.alicloud.oss.bucket.name}")
private String bucketName;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endPoint;
/**
* 上传文件到阿里云 OSS
*/
@PostMapping("/image/AliYunImgUpload")
public ResponseEntity<String> fileUpload(@RequestParam("file") MultipartFile file) {
try {
String fileName = new Date().getTime() + "-" + file.getOriginalFilename(); // 使用时间戳避免文件名冲突
// 文件上传
ossClient.putObject(bucketName, fileName, file.getInputStream());
return ResponseEntity.ok(fileName);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
/**
* 从阿里云 OSS 取回文件
*/
@GetMapping("/image/AliYunImgDownload")
public ResponseEntity<String> fileDownload(@RequestParam("fileName") String fileName) {
try {
// 设置预签名 URL 的过期时间(例如 1 小时)
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
// 生成预签名 URL
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName);
request.setExpiration(expiration);
URL url = ossClient.generatePresignedUrl(request);
// 返回预签名 URL
return ResponseEntity.ok(url.toString());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
}
8.启动服务后前端选择上传文件到oss
9.oss刷新后能看到上传的文件
10.将oss中文件名复制
11.回显成功
最后:
目前仅仅只是通过文件名直接访问oss拿取文件,实际应当先根据用户身份从mysql数据库中拿取用户能够访问的文件名,之后再次访问oss,实际可将oss理解为一个以文件名+桶名为主键的数据库专门用于存储大规模数据以减少本地数据库压力。后续会继续完善以及合并。