vue+springboot(Controller、Service、Dao、Entity、Mapper)实现观看视频功能
时间: 2025-04-07 15:10:46 浏览: 18
### Vue 和 Spring Boot 实现视频播放功能
#### 后端设计 (Spring Boot)
1. **Controller 层**
控制器负责接收前端请求并返回数据。以下是基于 `@RestController` 的控制器示例,用于提供视频流服务。
```java
@RestController
@RequestMapping("/api/video")
public class VideoController {
private final VideoService videoService;
public VideoController(VideoService videoService) {
this.videoService = videoService;
}
@GetMapping("/{videoId}")
public ResponseEntity<Resource> getVideoStream(@PathVariable String videoId, HttpServletRequest request) throws IOException {
Resource resource = videoService.loadAsResource(videoId);
if (resource.exists() && resource.isReadable()) {
HttpHeaders headers = new HttpHeaders();
long rangeStart = 0;
long rangeEnd = resource.contentLength();
String rangeHeader = request.getHeader("Range");
if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
String[] ranges = rangeHeader.substring(6).split("-");
rangeStart = Long.parseLong(ranges[0]);
if (ranges.length > 1) {
rangeEnd = Math.min(Long.parseLong(ranges[1]), resource.contentLength());
}
}
byte[] data = Files.readAllBytes(resource.getFile().toPath());
return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
.header(HttpHeaders.CONTENT_TYPE, "video/mp4")
.header(HttpHeaders.ACCEPT_RANGES, "bytes")
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(rangeEnd - rangeStart + 1))
.header(HttpHeaders.CONTENT_RANGE, "bytes " + rangeStart + "-" + rangeEnd + "/" + resource.contentLength())
.body(new ByteArrayResource(data));
} else {
throw new RuntimeException("File not found or unreadable!");
}
}
}
```
2. **Service 层**
Service 负责业务逻辑处理,例如加载资源文件。
```java
@Service
public class VideoService {
@Value("${file.upload.dir}")
private String uploadDir;
public Resource loadAsResource(String filename) throws MalformedURLException {
Path fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
try {
Path filePath = fileStorageLocation.resolve(filename).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("Could not read the file!");
}
} catch (MalformedURLException ex) {
throw new RuntimeException("Error: " + ex.getMessage());
}
}
}
```
3. **Entity 层**
定义实体类表示数据库表结构。
```java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "videos")
public class VideoEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String path;
// Getters and Setters omitted for brevity.
}
```
4. **DAO/Repository 层**
使用 JPA Repository 来定义 CRUD 方法。
```java
@Repository
public interface VideoRepository extends JpaRepository<VideoEntity, Long> {
Optional<VideoEntity> findByName(String name);
}
```
5. **Mapper 层**
如果需要 DTO 映射,则可以引入 MapStruct 或手动编写 Mapper 类。
---
#### 前端设计 (Vue.js)
1. **HTML 结构**
创建一个简单的 HTML 页面来嵌入 `<video>` 标签。
```html
<template>
<div>
<h1>{{ title }}</h1>
<video controls width="800">
<source :src="videoUrl" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Video Player',
videoUrl: '/api/video/sample.mp4' // 替换为实际路径
};
},
mounted() {
console.log('Component loaded');
}
};
</script>
```
2. **Axios 请求**
可以通过 Axios 获取动态 URL 并更新到页面上。
```javascript
import axios from 'axios';
export default {
data() {
return {
videoUrl: ''
};
},
async created() {
const response = await axios.get('/api/videos/list'); // 列出所有视频
if (response.data.length > 0) {
this.videoUrl = `/api/video/${response.data[0].id}`;
}
}
};
```
---
#### 数据库设计
创建一张存储视频元信息的表格:
```sql
CREATE TABLE videos (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
path VARCHAR(255) NOT NULL UNIQUE
);
```
---
### 技术要点说明
- 视频流支持断点续传和范围请求(Range Header),这可以通过设置 HTTP Headers 实现[^1]。
- 文件上传目录需配置在 application.properties 中以便于管理和部署[^2]。
```properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
file.upload.dir=/path/to/upload/directory/
```
- DAO 层采用 Spring Data JPA 提供的基础接口简化开发流程[^3]。
- 封装、继承、多态等 OOP 特性有助于提高代码可维护性和扩展性[^4]。
---
阅读全文
相关推荐


















