文件删除原创
# 后端
# CosManager.java
/**
*删除对象
*
* @param key 唯一键
*/
public void deleteObjects(String key) {
// 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
COSClient cosClient = createCOSClient();
//删除文件
DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucket,key);
cosClient.deleteObject(deleteObjectRequest);
// 确认本进程不再使用 cosClient 实例之后,关闭即可
cosClient.shutdown();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# CosController.java
/**
* 文件删除
*
* @param uploadFileRequest 对象在cos中的url
* @return 用户id
*/
@Operation(summary = "文件删除")
@PostMapping("/delete")
public BaseResponse deleteCos(@RequestBody UploadFileRequest uploadFileRequest, HttpServletRequest request) {
userService.getLoginUser(request);
String filepath = uploadFileRequest.getFilepath();
String key = filepath.replace(HOST, "");
try {
boolean objectExists = cosClient.doesObjectExist(cosClientConfig.getBucket(), key);
if (!objectExists) {
// 如果对象不存在,返回相应的响应
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "对象不存在");
}
// 尝试删除对象
cosManager.deleteObjects(key);
// 如果删除成功,返回成功响应
return ResultUtils.success(key);
} catch (Exception e) {
// 捕获并处理异常
log.error("file delete error, key = {}", key);
// 返回包含错误信息的响应
return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"删除文件时发生异常: " + e.getMessage());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 前端
基于vue3 + ts + elementplus
# 接口
/**
* 文件删除
* @param requestBody
* @returns BaseResponse OK
* @throws ApiError
*/
public static deleteCos(
requestBody: UploadFileRequest,
): CancelablePromise<BaseResponse> {
return __request(OpenAPI, {
method: 'POST',
url: '/cos/delete',
body: requestBody,
mediaType: 'application/json',
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 使用
html
<el-button type="primary" @click="deleteFile">删除</el-button>
1
ts
function deleteUser({ $index, row }) {
return new Promise((resolve, reject) => {
UserControllerService.deleteCos({filepath: row.key}).then(res => {
tableData.value.splice($index, 1)
ElMessage({
message: '删除成功',
type: 'success',
duration: 5 * 1000
})
getUser()
resolve(res.data)
}).catch((error) => {
reject(error);
})
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上次更新: 2024/01/11 18:04:10
- 01
- element-plus多文件手动上传 原创11-03
- 02
- TrueLicense 创建及安装证书 原创10-25
- 03
- 手动修改迅捷配置 原创09-03
- 04
- 安装 acme.sh 原创08-29
- 05
- zabbix部署 原创08-20