Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
practical_train
Commits
5ed2d743
Commit
5ed2d743
authored
Aug 04, 2026
by
王蔡翾
Browse files
Harden file upload and streaming download handling
parent
18dbe93d
Changes
13
Hide whitespace changes
Inline
Side-by-side
practical-api/practical-business-api/src/main/java/com/platform/business/model/dto/TeachingResourceDTO.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.model.dto
;
import
com.platform.business.model.entity.TeachingResourceEntity
;
import
lombok.Data
;
import
lombok.EqualsAndHashCode
;
/**
* 教学资源查询及编辑参数。
* 继承实体字段,用 resourceType、resourceName、courseId 等承载筛选或编辑数据。
*/
@Data
@EqualsAndHashCode
(
callSuper
=
true
)
public
class
TeachingResourceDTO
extends
TeachingResourceEntity
{
private
int
pageNum
;
private
int
pageSize
;
/** 资源名称或课程名称的模糊搜索关键字。 */
private
String
keyword
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/entity/BsFileEntity.java
View file @
5ed2d743
...
@@ -3,6 +3,7 @@ package com.platform.business.model.entity;
...
@@ -3,6 +3,7 @@ package com.platform.business.model.entity;
import
com.baomidou.mybatisplus.annotation.IdType
;
import
com.baomidou.mybatisplus.annotation.IdType
;
import
com.baomidou.mybatisplus.annotation.TableField
;
import
com.baomidou.mybatisplus.annotation.TableField
;
import
com.baomidou.mybatisplus.annotation.TableId
;
import
com.baomidou.mybatisplus.annotation.TableId
;
import
com.baomidou.mybatisplus.annotation.TableLogic
;
import
com.baomidou.mybatisplus.annotation.TableName
;
import
com.baomidou.mybatisplus.annotation.TableName
;
import
lombok.AllArgsConstructor
;
import
lombok.AllArgsConstructor
;
import
lombok.Builder
;
import
lombok.Builder
;
...
@@ -29,4 +30,9 @@ public class BsFileEntity {
...
@@ -29,4 +30,9 @@ public class BsFileEntity {
@TableField
(
"file_name"
)
@TableField
(
"file_name"
)
private
String
fileName
;
private
String
fileName
;
/** 文件逻辑删除标记;删除教学资源时不删除磁盘上的物理文件。 */
@TableLogic
(
value
=
"0"
,
delval
=
"1"
)
@TableField
(
"del_flag"
)
private
Integer
delFlag
;
}
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/entity/TeachingResourceEntity.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.model.entity
;
import
com.baomidou.mybatisplus.annotation.FieldFill
;
import
com.baomidou.mybatisplus.annotation.IdType
;
import
com.baomidou.mybatisplus.annotation.TableField
;
import
com.baomidou.mybatisplus.annotation.TableId
;
import
com.baomidou.mybatisplus.annotation.TableLogic
;
import
com.baomidou.mybatisplus.annotation.TableName
;
import
com.fasterxml.jackson.annotation.JsonFormat
;
import
lombok.Data
;
import
java.util.Date
;
/**
* 教学资源持久化实体。
*
* <p>资源本身与 {@code bs_file} 文件记录分离保存,通过 {@code fileId} 关联;
* {@code courseId} 绑定具体的 {@link ClassSubjectEntity} 课程。</p>
*/
@Data
@TableName
(
"teaching_resource"
)
public
class
TeachingResourceEntity
{
/** 本模块新增主键,使用 MyBatis-Plus 雪花算法生成字符串ID。 */
@TableId
(
value
=
"id"
,
type
=
IdType
.
ASSIGN_ID
)
private
String
id
;
/** 文件记录ID,关联 bs_file.id。 */
@TableField
(
"file_id"
)
private
Integer
fileId
;
/** 前端展示的资源名称,可与原始文件名不同。 */
@TableField
(
"resource_name"
)
private
String
resourceName
;
/** 资源类型:doc、video、image、other。 */
@TableField
(
"resource_type"
)
private
String
resourceType
;
/** 适用课程ID,关联 class_subject.id。 */
@TableField
(
"course_id"
)
private
Integer
courseId
;
/** 文件大小,单位为字节。 */
@TableField
(
"file_size"
)
private
Long
fileSize
;
@TableField
(
"uploader_id"
)
private
String
uploaderId
;
@TableField
(
"uploader_name"
)
private
String
uploaderName
;
@TableField
(
"download_count"
)
private
Long
downloadCount
;
/** 逻辑删除标记:0正常,1删除。 */
@TableLogic
(
value
=
"0"
,
delval
=
"1"
)
@TableField
(
"del_flag"
)
private
Integer
delFlag
;
@JsonFormat
(
pattern
=
"yyyy-MM-dd HH:mm:ss"
,
timezone
=
"GMT+8"
)
@TableField
(
value
=
"create_time"
,
fill
=
FieldFill
.
INSERT
)
private
Date
createTime
;
@JsonFormat
(
pattern
=
"yyyy-MM-dd HH:mm:ss"
,
timezone
=
"GMT+8"
)
@TableField
(
value
=
"update_time"
,
fill
=
FieldFill
.
INSERT_UPDATE
)
private
Date
updateTime
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/vo/TeachingResourceStatisticsVO.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.model.vo
;
import
lombok.Data
;
/**
* 教学资源统计数据;学生端返回值只统计当前学生有权查看的课程资源。
*/
@Data
public
class
TeachingResourceStatisticsVO
{
private
Long
totalCount
;
private
Long
totalSize
;
private
Long
totalDownloads
;
private
Long
docCount
;
private
Long
videoCount
;
private
Long
imageCount
;
private
Long
otherCount
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/vo/TeachingResourceVO.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.model.vo
;
import
com.fasterxml.jackson.annotation.JsonFormat
;
import
lombok.Data
;
import
java.util.Date
;
/**
* 教学资源列表返回对象,补充课程名称及班级信息供两端展示。
*/
@Data
public
class
TeachingResourceVO
{
private
String
id
;
private
Integer
fileId
;
private
String
resourceName
;
private
String
resourceType
;
private
Integer
courseId
;
private
String
courseName
;
private
Integer
classId
;
private
String
className
;
private
Long
fileSize
;
private
String
uploaderId
;
private
String
uploaderName
;
private
Long
downloadCount
;
@JsonFormat
(
pattern
=
"yyyy-MM-dd HH:mm:ss"
,
timezone
=
"GMT+8"
)
private
Date
createTime
;
}
practical-business/src/main/java/com/platform/business/controller/TeachingResourceController.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.controller
;
import
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
;
import
com.platform.business.model.dto.TeachingResourceDTO
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TeachingResourceStatisticsVO
;
import
com.platform.business.model.vo.TeachingResourceVO
;
import
com.platform.business.service.TeachingResourceService
;
import
com.platform.business.service.UserService
;
import
com.platform.business.utils.JwtTokenUtil
;
import
com.platform.controller.BaseController
;
import
com.platform.exception.BusinessException
;
import
com.platform.model.resp.Result
;
import
com.platform.page.TableDataInfo
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiOperation
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.bind.annotation.DeleteMapping
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.PutMapping
;
import
org.springframework.web.bind.annotation.RequestBody
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
org.springframework.web.multipart.MultipartFile
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletRequest
;
/**
* 教学资源接口。
* 管理员接口使用全量数据范围,学生接口始终根据登录令牌解析当前用户,
* 不接受前端传入的学生ID。
*/
@Api
(
tags
=
"教学资源"
)
@RestController
@RequestMapping
(
"/teaching/resource"
)
public
class
TeachingResourceController
extends
BaseController
{
@Resource
private
TeachingResourceService
teachingResourceService
;
@Resource
private
UserService
userService
;
@Resource
private
JwtTokenUtil
jwtTokenUtil
;
@ApiOperation
(
"管理员端-教学资源分页"
)
@PostMapping
(
"/admin/page"
)
public
TableDataInfo
adminPage
(
@RequestBody
TeachingResourceDTO
query
)
{
// 沿用项目现有 BaseController + PageHelper 的分页响应格式。
normalizePage
(
query
);
startPage
(
query
.
getPageNum
(),
query
.
getPageSize
());
return
getDataTable
(
teachingResourceService
.
adminList
(
query
));
}
@ApiOperation
(
"管理员端-教学资源统计"
)
@GetMapping
(
"/admin/statistics"
)
public
Result
<
TeachingResourceStatisticsVO
>
adminStatistics
()
{
return
Result
.
data
(
teachingResourceService
.
adminStatistics
());
}
@ApiOperation
(
"管理员端-上传教学资源"
)
@PostMapping
(
"/admin/upload"
)
public
Result
<
TeachingResourceVO
>
upload
(
@RequestParam
(
"file"
)
MultipartFile
file
,
@RequestParam
(
"resourceName"
)
String
resourceName
,
@RequestParam
(
"courseId"
)
Integer
courseId
,
HttpServletRequest
request
)
{
// 上传者信息只从服务端登录态获取,避免伪造上传人。
return
Result
.
data
(
teachingResourceService
.
upload
(
file
,
resourceName
,
courseId
,
currentUser
(
request
)));
}
@ApiOperation
(
"管理员端-编辑教学资源名称和适用课程"
)
@PutMapping
(
"/admin/update"
)
public
Result
<
Boolean
>
update
(
@RequestBody
TeachingResourceDTO
resource
)
{
return
Result
.
data
(
teachingResourceService
.
updateResource
(
resource
));
}
@ApiOperation
(
"管理员端-逻辑删除教学资源"
)
@DeleteMapping
(
"/admin/{id}"
)
public
Result
<
Boolean
>
delete
(
@PathVariable
String
id
)
{
return
Result
.
data
(
teachingResourceService
.
deleteResource
(
id
));
}
@ApiOperation
(
"管理员端-下载教学资源"
)
@GetMapping
(
"/admin/download/{id}"
)
public
void
adminDownload
(
@PathVariable
String
id
)
{
teachingResourceService
.
adminDownload
(
id
);
}
@ApiOperation
(
"学生端-本人班级课程资源分页"
)
@PostMapping
(
"/student/page"
)
public
TableDataInfo
studentPage
(
@RequestBody
TeachingResourceDTO
query
,
HttpServletRequest
request
)
{
normalizePage
(
query
);
// 先由令牌确定学生,再由 Mapper 查询该学生所在班级及对应课程资源。
UserEntity
student
=
currentUser
(
request
);
startPage
(
query
.
getPageNum
(),
query
.
getPageSize
());
return
getDataTable
(
teachingResourceService
.
studentList
(
student
.
getId
(),
query
));
}
@ApiOperation
(
"学生端-本人班级课程资源统计"
)
@GetMapping
(
"/student/statistics"
)
public
Result
<
TeachingResourceStatisticsVO
>
studentStatistics
(
HttpServletRequest
request
)
{
return
Result
.
data
(
teachingResourceService
.
studentStatistics
(
currentUser
(
request
).
getId
()));
}
@ApiOperation
(
"学生端-下载本人班级课程资源"
)
@GetMapping
(
"/student/download/{id}"
)
public
void
studentDownload
(
@PathVariable
String
id
,
HttpServletRequest
request
)
{
teachingResourceService
.
studentDownload
(
id
,
currentUser
(
request
).
getId
());
}
/**
* 从 Authorization 头解析手机号并查询当前有效用户。
* 同时兼容项目原有裸 token 和标准 Bearer token 两种传递方式。
*/
private
UserEntity
currentUser
(
HttpServletRequest
request
)
{
String
token
=
request
.
getHeader
(
"Authorization"
);
if
(!
StringUtils
.
hasText
(
token
))
{
throw
new
BusinessException
(
"未获取到登录凭证"
);
}
if
(
token
.
startsWith
(
"Bearer "
))
{
token
=
token
.
substring
(
7
);
}
String
phoneNumber
=
jwtTokenUtil
.
getUsernameFromToken
(
token
);
UserEntity
user
=
userService
.
getOne
(
new
LambdaQueryWrapper
<
UserEntity
>()
.
eq
(
UserEntity:
:
getPhoneNumber
,
phoneNumber
)
.
eq
(
UserEntity:
:
getDelFlag
,
false
));
if
(
user
==
null
)
{
throw
new
BusinessException
(
"当前登录用户不存在"
);
}
return
user
;
}
/**
* 补充分页默认值并限制单页最大100条,防止一次查询数据量过大。
*/
private
void
normalizePage
(
TeachingResourceDTO
query
)
{
if
(
query
==
null
)
{
throw
new
BusinessException
(
"分页参数不能为空"
);
}
if
(
query
.
getPageNum
()
<=
0
)
{
query
.
setPageNum
(
1
);
}
if
(
query
.
getPageSize
()
<=
0
)
{
query
.
setPageSize
(
20
);
}
if
(
query
.
getPageSize
()
>
100
)
{
query
.
setPageSize
(
100
);
}
}
}
practical-business/src/main/java/com/platform/business/mapper/TeachingResourceMapper.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.dto.TeachingResourceDTO
;
import
com.platform.business.model.entity.TeachingResourceEntity
;
import
com.platform.business.model.vo.TeachingResourceStatisticsVO
;
import
com.platform.business.model.vo.TeachingResourceVO
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.List
;
/**
* 教学资源数据访问接口。
* 列表和统计查询通过课程所属班级控制学生的数据范围。
*/
@Mapper
public
interface
TeachingResourceMapper
extends
BaseMapper
<
TeachingResourceEntity
>
{
/** 管理员端全量分页查询,分页由 Controller 中的 PageHelper 启动。 */
List
<
TeachingResourceVO
>
selectAdminList
(
@Param
(
"query"
)
TeachingResourceDTO
query
);
/** 学生端分页查询,只返回该学生所在班级对应课程的资源。 */
List
<
TeachingResourceVO
>
selectStudentList
(
@Param
(
"userId"
)
String
userId
,
@Param
(
"query"
)
TeachingResourceDTO
query
);
/** 查询单条未删除资源及其课程、班级展示信息。 */
TeachingResourceVO
selectAdminById
(
@Param
(
"id"
)
String
id
);
/** 判断指定资源是否属于学生所在班级的课程,用于下载前二次鉴权。 */
int
countStudentResource
(
@Param
(
"id"
)
String
id
,
@Param
(
"userId"
)
String
userId
);
/** 管理员端全量资源统计。 */
TeachingResourceStatisticsVO
selectAdminStatistics
();
/** 学生端可见范围资源统计。 */
TeachingResourceStatisticsVO
selectStudentStatistics
(
@Param
(
"userId"
)
String
userId
);
/** 原子递增下载次数,避免并发下载时计数丢失。 */
int
incrementDownloadCount
(
@Param
(
"id"
)
String
id
);
}
practical-business/src/main/java/com/platform/business/service/BsFileService.java
View file @
5ed2d743
...
@@ -7,7 +7,12 @@ import org.springframework.web.multipart.MultipartFile;
...
@@ -7,7 +7,12 @@ import org.springframework.web.multipart.MultipartFile;
public
interface
BsFileService
extends
IService
<
BsFileEntity
>
{
public
interface
BsFileService
extends
IService
<
BsFileEntity
>
{
/** 单文件最大500MB,业务层再次校验,避免仅依赖容器配置。 */
long
MAX_FILE_SIZE
=
500L
*
1024
*
1024
;
/** 将文件保存到磁盘并持久化文件元数据。 */
BsFileEntity
uploadFile
(
MultipartFile
file
)
;
BsFileEntity
uploadFile
(
MultipartFile
file
)
;
/** 以附件方式流式输出文件。 */
void
downloadFile
(
Integer
id
);
void
downloadFile
(
Integer
id
);
}
}
practical-business/src/main/java/com/platform/business/service/TeachingResourceService.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.service
;
import
com.baomidou.mybatisplus.extension.service.IService
;
import
com.platform.business.model.dto.TeachingResourceDTO
;
import
com.platform.business.model.entity.TeachingResourceEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TeachingResourceStatisticsVO
;
import
com.platform.business.model.vo.TeachingResourceVO
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.util.List
;
/**
* 教学资源业务接口,分别提供管理员全量视角和学生本人班级视角。
*/
public
interface
TeachingResourceService
extends
IService
<
TeachingResourceEntity
>
{
/** 查询管理员端资源列表。 */
List
<
TeachingResourceVO
>
adminList
(
TeachingResourceDTO
query
);
/** 查询指定学生所在班级课程关联的资源列表。 */
List
<
TeachingResourceVO
>
studentList
(
String
userId
,
TeachingResourceDTO
query
);
/** 统计所有未删除的教学资源。 */
TeachingResourceStatisticsVO
adminStatistics
();
/** 统计指定学生有权查看的教学资源。 */
TeachingResourceStatisticsVO
studentStatistics
(
String
userId
);
/** 上传文件并创建与课程绑定的教学资源记录。 */
TeachingResourceVO
upload
(
MultipartFile
file
,
String
resourceName
,
Integer
courseId
,
UserEntity
uploader
);
/** 只修改资源名称及绑定课程,不替换文件。 */
boolean
updateResource
(
TeachingResourceDTO
resource
);
/** 同时逻辑删除教学资源记录和文件记录,保留物理文件。 */
boolean
deleteResource
(
String
id
);
/** 管理员下载资源并累计下载次数。 */
void
adminDownload
(
String
id
);
/** 校验学生班级课程权限后下载资源并累计下载次数。 */
void
studentDownload
(
String
id
,
String
userId
);
}
practical-business/src/main/java/com/platform/business/service/impl/BsFileServiceImpl.java
View file @
5ed2d743
...
@@ -5,71 +5,133 @@ import com.platform.business.mapper.BsFileMapper;
...
@@ -5,71 +5,133 @@ import com.platform.business.mapper.BsFileMapper;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.service.BsFileService
;
import
com.platform.business.service.BsFileService
;
import
com.platform.exception.BusinessException
;
import
com.platform.exception.BusinessException
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.MediaType
;
import
org.springframework.stereotype.Service
;
import
org.springframework.stereotype.Service
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
org.springframework.web.multipart.MultipartFile
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
javax.annotation.Resource
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletResponse
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.File
;
import
java.io.IOException
;
import
java.io.IOException
;
import
java.net.URLEncoder
;
import
java.net.URLEncoder
;
import
java.nio.charset.StandardCharsets
;
import
java.nio.file.Files
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.Path
;
import
java.nio.file.Paths
;
import
java.nio.file.Paths
;
import
java.util.UUID
;
/**
@Slf4j
* 本地文件存储实现。
* 使用随机存储名避免同名覆盖,数据库保留原始文件名用于下载响应。
*/
@Service
@Service
public
class
BsFileServiceImpl
extends
ServiceImpl
<
BsFileMapper
,
BsFileEntity
>
implements
BsFileService
{
public
class
BsFileServiceImpl
extends
ServiceImpl
<
BsFileMapper
,
BsFileEntity
>
implements
BsFileService
{
private
static
final
String
PREFIX
=
"/home/back/practical-train/file/"
;
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
BsFileServiceImpl
.
class
);
@Value
(
"${business.file.upload-dir:/home/back/practical-train/file}"
)
private
String
uploadDirectory
;
@Resource
private
HttpServletResponse
response
;
@Override
@Override
public
BsFileEntity
uploadFile
(
MultipartFile
file
)
{
public
BsFileEntity
uploadFile
(
MultipartFile
file
)
{
if
(
file
.
isEmpty
())
{
// 业务层校验500MB上限,防止容器上传限制被其他配置覆盖后失效。
throw
new
BusinessException
(
"文件为空"
);
if
(
file
==
null
||
file
.
isEmpty
())
{
throw
new
BusinessException
(
"上传文件不能为空"
);
}
if
(
file
.
getSize
()
>
MAX_FILE_SIZE
)
{
throw
new
BusinessException
(
"单个文件不能超过500MB"
);
}
}
try
{
try
{
//获取时间戳,保证不重复
// 创建并规范化上传目录,所有目标文件必须位于该目录之下。
// String time = System.currentTimeMillis() + "/";
Path
directory
=
Paths
.
get
(
uploadDirectory
).
toAbsolutePath
().
normalize
();
// 确保上传目录存在
Files
.
createDirectories
(
directory
);
// File uploadDir = new File(PREFIX + time);
File
uploadDir
=
new
File
(
PREFIX
);
// 原始文件名只用于展示;磁盘使用UUID文件名,避免重名覆盖和路径穿越。
if
(!
uploadDir
.
exists
())
{
String
originalFilename
=
safeOriginalFilename
(
file
.
getOriginalFilename
());
boolean
mkdir
=
uploadDir
.
mkdirs
();
String
storedFilename
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
)
log
.
info
(
"创建文件夹"
+
mkdir
);
+
getExtension
(
originalFilename
);
Path
target
=
directory
.
resolve
(
storedFilename
).
normalize
();
if
(!
target
.
startsWith
(
directory
))
{
throw
new
BusinessException
(
"文件保存路径非法"
);
}
}
// 保存文件到本地
// transferTo 直接流式落盘,避免大文件一次性加载到JVM内存。
// Path path = Paths.get(PREFIX + time + file.getOriginalFilename());
file
.
transferTo
(
target
.
toFile
());
Path
path
=
Paths
.
get
(
PREFIX
+
file
.
getOriginalFilename
());
Files
.
write
(
path
,
file
.
getBytes
());
//获取文件名
String
fileName
=
file
.
getOriginalFilename
();
//获取文件绝对路径
String
fileUrl
=
path
.
toAbsolutePath
().
toString
();
BsFileEntity
bsFile
=
BsFileEntity
.
builder
().
url
(
fileUrl
).
fileName
(
fileName
).
build
();
save
(
bsFile
);
return
bsFile
;
// 文件写入成功后保存元数据;数据库保存失败时清理本次产生的物理文件。
BsFileEntity
bsFile
=
BsFileEntity
.
builder
()
.
url
(
target
.
toString
())
.
fileName
(
originalFilename
)
.
delFlag
(
0
)
.
build
();
if
(!
save
(
bsFile
))
{
Files
.
deleteIfExists
(
target
);
throw
new
BusinessException
(
"文件信息保存失败"
);
}
return
bsFile
;
}
catch
(
IOException
e
)
{
}
catch
(
IOException
e
)
{
log
.
error
(
"文件上传失败"
,
e
);
throw
new
BusinessException
(
"文件上传失败"
);
throw
new
BusinessException
(
"文件上传失败"
);
}
}
}
}
@Resource
private
HttpServletResponse
response
;
@Override
@Override
public
void
downloadFile
(
Integer
id
)
{
public
void
downloadFile
(
Integer
id
)
{
// getById 会自动附带 del_flag=0 条件,已逻辑删除的文件不可下载。
BsFileEntity
bsFile
=
getById
(
id
);
if
(
bsFile
==
null
||
!
StringUtils
.
hasText
(
bsFile
.
getUrl
()))
{
throw
new
BusinessException
(
"文件不存在或已删除"
);
}
try
{
try
{
BsFileEntity
bsFile
=
getById
(
id
);
Path
path
=
Paths
.
get
(
bsFile
.
getUrl
()).
toAbsolutePath
().
normalize
();
String
url
=
bsFile
.
getUrl
();
if
(!
Files
.
isRegularFile
(
path
))
{
byte
[]
bytes
=
Files
.
readAllBytes
(
Paths
.
get
(
url
));
throw
new
BusinessException
(
"文件不存在或已删除"
);
response
.
setHeader
(
HttpHeaders
.
CONTENT_DISPOSITION
,
"attachment; filename="
+
URLEncoder
.
encode
(
bsFile
.
getFileName
(),
"utf-8"
));
}
response
.
getOutputStream
().
write
(
bytes
);
String
contentType
=
Files
.
probeContentType
(
path
);
response
.
setContentType
(
StringUtils
.
hasText
(
contentType
)
?
contentType
:
MediaType
.
APPLICATION_OCTET_STREAM_VALUE
);
response
.
setContentLengthLong
(
Files
.
size
(
path
));
String
encodedFilename
=
URLEncoder
.
encode
(
safeDownloadFilename
(
bsFile
.
getFileName
()),
StandardCharsets
.
UTF_8
.
name
()).
replace
(
"+"
,
"%20"
);
response
.
setHeader
(
HttpHeaders
.
CONTENT_DISPOSITION
,
"attachment; filename*=UTF-8''"
+
encodedFilename
);
// 以流的方式复制到响应,支持接近500MB的大文件且不占用同等堆内存。
Files
.
copy
(
path
,
response
.
getOutputStream
());
response
.
getOutputStream
().
flush
();
}
catch
(
IOException
e
)
{
}
catch
(
IOException
e
)
{
log
.
error
(
"文件下载失败,文件ID:{}"
,
id
,
e
);
throw
new
BusinessException
(
"文件下载失败"
);
throw
new
BusinessException
(
"文件下载失败"
);
}
}
}
}
/** 去除客户端路径信息和换行符,仅保留安全的原始文件名。 */
private
String
safeOriginalFilename
(
String
originalFilename
)
{
if
(!
StringUtils
.
hasText
(
originalFilename
))
{
return
"unnamed-file"
;
}
String
normalized
=
originalFilename
.
replace
(
'\\'
,
'/'
);
String
filename
=
normalized
.
substring
(
normalized
.
lastIndexOf
(
'/'
)
+
1
).
trim
();
filename
=
safeDownloadFilename
(
filename
);
return
StringUtils
.
hasText
(
filename
)
?
filename
:
"unnamed-file"
;
}
/** 移除响应头文件名中的换行符,防止响应头注入。 */
private
String
safeDownloadFilename
(
String
filename
)
{
if
(
filename
==
null
)
{
return
"unnamed-file"
;
}
return
filename
.
replace
(
"\r"
,
""
).
replace
(
"\n"
,
""
);
}
/** 保留原始扩展名,使磁盘文件仍可被系统识别类型。 */
private
String
getExtension
(
String
filename
)
{
int
dotIndex
=
filename
.
lastIndexOf
(
'.'
);
return
dotIndex
>=
0
?
filename
.
substring
(
dotIndex
)
:
""
;
}
}
}
practical-business/src/main/java/com/platform/business/service/impl/TeachingResourceServiceImpl.java
0 → 100644
View file @
5ed2d743
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.platform.business.mapper.TeachingResourceMapper
;
import
com.platform.business.model.dto.TeachingResourceDTO
;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.model.entity.ClassSubjectEntity
;
import
com.platform.business.model.entity.TeachingResourceEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TeachingResourceStatisticsVO
;
import
com.platform.business.model.vo.TeachingResourceVO
;
import
com.platform.business.service.BsFileService
;
import
com.platform.business.service.ClassSubjectService
;
import
com.platform.business.service.TeachingResourceService
;
import
com.platform.exception.BusinessException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
javax.annotation.Resource
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Set
;
/**
* 教学资源核心业务实现。
*
* <p>管理员查询全部资源;学生查询及下载时,均根据当前用户所在班级和
* {@code class_subject.class_id} 限制资源范围。</p>
*/
@Service
public
class
TeachingResourceServiceImpl
extends
ServiceImpl
<
TeachingResourceMapper
,
TeachingResourceEntity
>
implements
TeachingResourceService
{
/** 文件扩展名与原型资源类型之间的映射。未知扩展名统一归为 other。 */
private
static
final
Set
<
String
>
DOCUMENT_EXTENSIONS
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"pdf"
,
"doc"
,
"docx"
,
"xls"
,
"xlsx"
,
"ppt"
,
"pptx"
,
"txt"
,
"csv"
)));
private
static
final
Set
<
String
>
VIDEO_EXTENSIONS
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"mp4"
,
"avi"
,
"mov"
,
"wmv"
,
"flv"
,
"mkv"
,
"m4v"
,
"webm"
)));
private
static
final
Set
<
String
>
IMAGE_EXTENSIONS
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"jpg"
,
"jpeg"
,
"png"
,
"gif"
,
"bmp"
,
"webp"
,
"svg"
)));
private
static
final
Set
<
String
>
RESOURCE_TYPES
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"all"
,
"doc"
,
"video"
,
"image"
,
"other"
)));
@Resource
private
BsFileService
bsFileService
;
@Resource
private
ClassSubjectService
classSubjectService
;
@Override
public
List
<
TeachingResourceVO
>
adminList
(
TeachingResourceDTO
query
)
{
// 统一清洗关键字和资源类型,避免各查询入口出现不同筛选规则。
normalizeQuery
(
query
);
return
baseMapper
.
selectAdminList
(
query
);
}
@Override
public
List
<
TeachingResourceVO
>
studentList
(
String
userId
,
TeachingResourceDTO
query
)
{
requireUserId
(
userId
);
normalizeQuery
(
query
);
// Mapper 使用 class_student 与 class_subject 关系限制学生可见范围。
return
baseMapper
.
selectStudentList
(
userId
,
query
);
}
@Override
public
TeachingResourceStatisticsVO
adminStatistics
()
{
return
baseMapper
.
selectAdminStatistics
();
}
@Override
public
TeachingResourceStatisticsVO
studentStatistics
(
String
userId
)
{
requireUserId
(
userId
);
return
baseMapper
.
selectStudentStatistics
(
userId
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TeachingResourceVO
upload
(
MultipartFile
file
,
String
resourceName
,
Integer
courseId
,
UserEntity
uploader
)
{
// 第一步:先校验展示名称和课程ID,保证资源绑定的是有效 ClassSubjectEntity。
validateResourceName
(
resourceName
);
ClassSubjectEntity
course
=
requireCourse
(
courseId
);
if
(
file
==
null
||
file
.
isEmpty
())
{
throw
new
BusinessException
(
"上传文件不能为空"
);
}
if
(
uploader
==
null
||
!
StringUtils
.
hasText
(
uploader
.
getId
()))
{
throw
new
BusinessException
(
"无法获取当前上传用户"
);
}
// 第二步:根据原始文件扩展名确定类型,再保存文件并取得 bs_file.id。
String
resourceType
=
resolveResourceType
(
file
.
getOriginalFilename
());
BsFileEntity
storedFile
=
bsFileService
.
uploadFile
(
file
);
// 第三步:保存资源业务信息。String 主键由 ASSIGN_ID 雪花算法自动填充。
TeachingResourceEntity
resource
=
new
TeachingResourceEntity
();
resource
.
setFileId
(
storedFile
.
getId
());
resource
.
setResourceName
(
resourceName
.
trim
());
resource
.
setResourceType
(
resourceType
);
resource
.
setCourseId
(
course
.
getId
());
resource
.
setFileSize
(
file
.
getSize
());
resource
.
setUploaderId
(
uploader
.
getId
());
resource
.
setUploaderName
(
resolveUploaderName
(
uploader
));
resource
.
setDownloadCount
(
0L
);
resource
.
setDelFlag
(
0
);
if
(!
save
(
resource
))
{
throw
new
BusinessException
(
"教学资源保存失败"
);
}
// 返回包含课程名、班级名的完整展示对象,上传后前端可直接刷新列表。
return
baseMapper
.
selectAdminById
(
resource
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
updateResource
(
TeachingResourceDTO
resource
)
{
// 编辑接口不接收新文件,只允许更新原型要求的资源名称和课程ID。
if
(
resource
==
null
||
resource
.
getId
()
==
null
)
{
throw
new
BusinessException
(
"资源ID不能为空"
);
}
validateResourceName
(
resource
.
getResourceName
());
requireCourse
(
resource
.
getCourseId
());
requireResource
(
resource
.
getId
());
TeachingResourceEntity
update
=
new
TeachingResourceEntity
();
update
.
setId
(
resource
.
getId
());
update
.
setResourceName
(
resource
.
getResourceName
().
trim
());
update
.
setCourseId
(
resource
.
getCourseId
());
if
(!
updateById
(
update
))
{
throw
new
BusinessException
(
"教学资源更新失败"
);
}
return
true
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
deleteResource
(
String
id
)
{
// 删除前同时确认资源和文件记录存在,避免出现只删除一侧的不一致状态。
TeachingResourceEntity
resource
=
requireResource
(
id
);
BsFileEntity
storedFile
=
bsFileService
.
getById
(
resource
.
getFileId
());
if
(
storedFile
==
null
)
{
throw
new
BusinessException
(
"资源文件不存在或已删除"
);
}
// 两个实体均配置 @TableLogic,此处只更新删除标记,不删除磁盘物理文件。
if
(!
removeById
(
id
))
{
throw
new
BusinessException
(
"教学资源删除失败"
);
}
if
(!
bsFileService
.
removeById
(
resource
.
getFileId
()))
{
throw
new
BusinessException
(
"资源文件删除失败"
);
}
return
true
;
}
@Override
public
void
adminDownload
(
String
id
)
{
TeachingResourceEntity
resource
=
requireResource
(
id
);
downloadAndCount
(
resource
);
}
@Override
public
void
studentDownload
(
String
id
,
String
userId
)
{
requireUserId
(
userId
);
TeachingResourceEntity
resource
=
requireResource
(
id
);
// 列表过滤不能代替下载鉴权,防止学生通过猜测资源ID越权下载。
if
(
baseMapper
.
countStudentResource
(
id
,
userId
)
==
0
)
{
throw
new
BusinessException
(
"无权下载非本人班级课程的资源"
);
}
downloadAndCount
(
resource
);
}
/**
* 文件流成功写出后原子递增下载次数;写出失败时不会累计。
*/
private
void
downloadAndCount
(
TeachingResourceEntity
resource
)
{
bsFileService
.
downloadFile
(
resource
.
getFileId
());
if
(
baseMapper
.
incrementDownloadCount
(
resource
.
getId
())
!=
1
)
{
throw
new
BusinessException
(
"下载次数更新失败"
);
}
}
/** 查询未逻辑删除的资源,不存在时统一抛出业务异常。 */
private
TeachingResourceEntity
requireResource
(
String
id
)
{
if
(!
StringUtils
.
hasText
(
id
))
{
throw
new
BusinessException
(
"资源ID不能为空"
);
}
TeachingResourceEntity
resource
=
getById
(
id
);
if
(
resource
==
null
)
{
throw
new
BusinessException
(
"教学资源不存在或已删除"
);
}
return
resource
;
}
/** 校验上传或编辑时绑定的课程ID真实存在。 */
private
ClassSubjectEntity
requireCourse
(
Integer
courseId
)
{
if
(
courseId
==
null
)
{
throw
new
BusinessException
(
"适用课程不能为空"
);
}
ClassSubjectEntity
course
=
classSubjectService
.
getById
(
courseId
);
if
(
course
==
null
)
{
throw
new
BusinessException
(
"适用课程不存在"
);
}
return
course
;
}
/** 校验必填的资源展示名称及数据库字段长度。 */
private
void
validateResourceName
(
String
resourceName
)
{
if
(!
StringUtils
.
hasText
(
resourceName
))
{
throw
new
BusinessException
(
"资源名称不能为空"
);
}
if
(
resourceName
.
trim
().
length
()
>
200
)
{
throw
new
BusinessException
(
"资源名称不能超过200个字符"
);
}
}
/** 标准化列表查询参数并拒绝原型定义之外的资源类型。 */
private
void
normalizeQuery
(
TeachingResourceDTO
query
)
{
if
(
query
==
null
)
{
throw
new
BusinessException
(
"查询条件不能为空"
);
}
if
(
StringUtils
.
hasText
(
query
.
getKeyword
()))
{
query
.
setKeyword
(
query
.
getKeyword
().
trim
());
}
if
(!
StringUtils
.
hasText
(
query
.
getResourceType
()))
{
query
.
setResourceType
(
"all"
);
}
else
{
String
resourceType
=
query
.
getResourceType
().
trim
().
toLowerCase
(
Locale
.
ROOT
);
if
(!
RESOURCE_TYPES
.
contains
(
resourceType
))
{
throw
new
BusinessException
(
"不支持的资源类型"
);
}
query
.
setResourceType
(
resourceType
);
}
}
/** 根据文件扩展名自动识别 doc、video、image、other 四类资源。 */
private
String
resolveResourceType
(
String
originalFilename
)
{
if
(!
StringUtils
.
hasText
(
originalFilename
))
{
return
"other"
;
}
String
filename
=
originalFilename
.
trim
();
int
dotIndex
=
filename
.
lastIndexOf
(
'.'
);
if
(
dotIndex
<
0
||
dotIndex
==
filename
.
length
()
-
1
)
{
return
"other"
;
}
String
extension
=
filename
.
substring
(
dotIndex
+
1
).
toLowerCase
(
Locale
.
ROOT
);
if
(
DOCUMENT_EXTENSIONS
.
contains
(
extension
))
{
return
"doc"
;
}
if
(
VIDEO_EXTENSIONS
.
contains
(
extension
))
{
return
"video"
;
}
if
(
IMAGE_EXTENSIONS
.
contains
(
extension
))
{
return
"image"
;
}
return
"other"
;
}
/** 按昵称、账号、手机号顺序确定列表中展示的上传者名称。 */
private
String
resolveUploaderName
(
UserEntity
uploader
)
{
if
(
StringUtils
.
hasText
(
uploader
.
getNickName
()))
{
return
uploader
.
getNickName
();
}
if
(
StringUtils
.
hasText
(
uploader
.
getUsername
()))
{
return
uploader
.
getUsername
();
}
return
uploader
.
getPhoneNumber
();
}
/** 学生数据范围查询必须使用服务端从令牌解析出的用户ID。 */
private
void
requireUserId
(
String
userId
)
{
if
(!
StringUtils
.
hasText
(
userId
))
{
throw
new
BusinessException
(
"无法获取当前学生信息"
);
}
}
}
practical-business/src/main/resources/bootstrap.yml
View file @
5ed2d743
spring
:
spring
:
profiles
:
profiles
:
active
:
dev
active
:
dev
servlet
:
multipart
:
max-file-size
:
500MB
max-request-size
:
510MB
practical-business/src/main/resources/com/platform/business/mapper/TeachingResourceMapper.xml
0 → 100644
View file @
5ed2d743
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace=
"com.platform.business.mapper.TeachingResourceMapper"
>
<!-- 列表公共字段:资源表关联文件、课程和班级,统一组装前端展示对象。 -->
<sql
id=
"resourceColumns"
>
tr.id,
tr.file_id AS fileId,
tr.resource_name AS resourceName,
tr.resource_type AS resourceType,
tr.course_id AS courseId,
cs.subject_name AS courseName,
cs.class_id AS classId,
c.name AS className,
tr.file_size AS fileSize,
tr.uploader_id AS uploaderId,
tr.uploader_name AS uploaderName,
tr.download_count AS downloadCount,
tr.create_time AS createTime
</sql>
<!-- 管理员端和学生端共用筛选条件,支持类型及资源名/课程名模糊搜索。 -->
<sql
id=
"resourceFilters"
>
<if
test=
"query.resourceType != null and query.resourceType != '' and query.resourceType != 'all'"
>
AND tr.resource_type = #{query.resourceType}
</if>
<if
test=
"query.keyword != null and query.keyword != ''"
>
AND (
tr.resource_name LIKE CONCAT('%', #{query.keyword}, '%')
OR cs.subject_name LIKE CONCAT('%', #{query.keyword}, '%')
)
</if>
</sql>
<!-- 管理员查看全部未逻辑删除且文件有效的资源。 -->
<select
id=
"selectAdminList"
resultType=
"com.platform.business.model.vo.TeachingResourceVO"
>
SELECT
<include
refid=
"resourceColumns"
/>
FROM teaching_resource tr
INNER JOIN bs_file bf ON bf.id = tr.file_id AND bf.del_flag = 0
INNER JOIN class_subject cs ON cs.id = tr.course_id
LEFT JOIN class c ON c.id = cs.class_id
WHERE tr.del_flag = 0
<include
refid=
"resourceFilters"
/>
ORDER BY tr.create_time DESC, tr.id DESC
</select>
<!--
学生数据范围:先通过 class_student 确认所在班级,
再匹配 class_subject.class_id,只返回本人班级课程关联资源。
-->
<select
id=
"selectStudentList"
resultType=
"com.platform.business.model.vo.TeachingResourceVO"
>
SELECT
<include
refid=
"resourceColumns"
/>
FROM teaching_resource tr
INNER JOIN bs_file bf ON bf.id = tr.file_id AND bf.del_flag = 0
INNER JOIN class_subject cs ON cs.id = tr.course_id
LEFT JOIN class c ON c.id = cs.class_id
WHERE tr.del_flag = 0
AND EXISTS (
SELECT 1
FROM class_student student_class
WHERE student_class.class_id = cs.class_id
AND student_class.user_id = #{userId}
)
<include
refid=
"resourceFilters"
/>
ORDER BY tr.create_time DESC, tr.id DESC
</select>
<select
id=
"selectAdminById"
resultType=
"com.platform.business.model.vo.TeachingResourceVO"
>
SELECT
<include
refid=
"resourceColumns"
/>
FROM teaching_resource tr
INNER JOIN bs_file bf ON bf.id = tr.file_id AND bf.del_flag = 0
INNER JOIN class_subject cs ON cs.id = tr.course_id
LEFT JOIN class c ON c.id = cs.class_id
WHERE tr.id = #{id}
AND tr.del_flag = 0
</select>
<!-- 下载前再次执行相同的数据范围校验,避免绕过列表接口越权下载。 -->
<select
id=
"countStudentResource"
resultType=
"java.lang.Integer"
>
SELECT COUNT(1)
FROM teaching_resource tr
INNER JOIN bs_file bf ON bf.id = tr.file_id AND bf.del_flag = 0
INNER JOIN class_subject cs ON cs.id = tr.course_id
WHERE tr.id = #{id}
AND tr.del_flag = 0
AND EXISTS (
SELECT 1
FROM class_student student_class
WHERE student_class.class_id = cs.class_id
AND student_class.user_id = #{userId}
)
</select>
<!-- 管理员KPI:资源总数、总大小、下载次数以及各类型数量。 -->
<select
id=
"selectAdminStatistics"
resultType=
"com.platform.business.model.vo.TeachingResourceStatisticsVO"
>
SELECT
COUNT(1) AS totalCount,
COALESCE(SUM(tr.file_size), 0) AS totalSize,
COALESCE(SUM(tr.download_count), 0) AS totalDownloads,
COALESCE(SUM(CASE WHEN tr.resource_type = 'doc' THEN 1 ELSE 0 END), 0) AS docCount,
COALESCE(SUM(CASE WHEN tr.resource_type = 'video' THEN 1 ELSE 0 END), 0) AS videoCount,
COALESCE(SUM(CASE WHEN tr.resource_type = 'image' THEN 1 ELSE 0 END), 0) AS imageCount,
COALESCE(SUM(CASE WHEN tr.resource_type = 'other' THEN 1 ELSE 0 END), 0) AS otherCount
FROM teaching_resource tr
INNER JOIN bs_file bf ON bf.id = tr.file_id AND bf.del_flag = 0
WHERE tr.del_flag = 0
</select>
<!-- 学生KPI与列表使用完全相同的班级课程数据范围。 -->
<select
id=
"selectStudentStatistics"
resultType=
"com.platform.business.model.vo.TeachingResourceStatisticsVO"
>
SELECT
COUNT(1) AS totalCount,
COALESCE(SUM(tr.file_size), 0) AS totalSize,
COALESCE(SUM(tr.download_count), 0) AS totalDownloads,
COALESCE(SUM(CASE WHEN tr.resource_type = 'doc' THEN 1 ELSE 0 END), 0) AS docCount,
COALESCE(SUM(CASE WHEN tr.resource_type = 'video' THEN 1 ELSE 0 END), 0) AS videoCount,
COALESCE(SUM(CASE WHEN tr.resource_type = 'image' THEN 1 ELSE 0 END), 0) AS imageCount,
COALESCE(SUM(CASE WHEN tr.resource_type = 'other' THEN 1 ELSE 0 END), 0) AS otherCount
FROM teaching_resource tr
INNER JOIN bs_file bf ON bf.id = tr.file_id AND bf.del_flag = 0
INNER JOIN class_subject cs ON cs.id = tr.course_id
WHERE tr.del_flag = 0
AND EXISTS (
SELECT 1
FROM class_student student_class
WHERE student_class.class_id = cs.class_id
AND student_class.user_id = #{userId}
)
</select>
<!-- 数据库原子自增,防止并发下载时出现读取后覆盖造成的计数丢失。 -->
<update
id=
"incrementDownloadCount"
>
UPDATE teaching_resource
SET download_count = download_count + 1,
update_time = CURRENT_TIMESTAMP
WHERE id = #{id}
AND del_flag = 0
</update>
</mapper>
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment