文件上传
youlai-aspnet 提供统一的文件上传服务,支持本地存储。
存储方式
通过配置切换存储方式:
| 存储类型 | 配置值 | 说明 |
|---|---|---|
| 本地存储 | local | 存储在服务器本地文件系统 |
接口说明
上传接口:
POST /api/v1/files
Content-Type: multipart/form-data| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
file | File | 是 | 表单文件对象 |
删除接口:
DELETE /api/v1/files?filePath={url}| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
filePath | String | 是 | 文件完整 URL |
响应结构:
json
{
"code": "00000",
"msg": "成功",
"data": {
"name": "原始文件名.png",
"url": "/upload/20250212/abc123.png"
}
}| 字段 | 说明 |
|---|---|
name | 原始文件名 |
url | 文件访问地址,前端直接使用 |
配置说明
本地存储
json
"FileStorage": {
"Type": "local",
"Local": {
"StoragePath": "/data/upload",
"BaseUrl": "http://localhost:8000"
}
}配置说明:
| 配置项 | 说明 |
|---|---|
StoragePath | 文件存储路径 |
BaseUrl | 访问基础 URL |
特点:
- 文件存储在服务器本地
- 返回相对路径,前端需拼接访问前缀
- 适用于单机部署、开发测试环境
文件命名规则
统一采用以下命名规则:
{dateFolder}/{uuid}.{suffix}| 组成 | 说明 | 示例 |
|---|---|---|
dateFolder | 日期文件夹 | 20250212 |
uuid | 唯一标识 | abc123def456 |
suffix | 文件后缀 | png |
示例:20250212/abc123def456.png
前端对接
Vue 3 + Element Plus
vue
<template>
<el-upload
action="/api/v1/files"
name="file"
:headers="{ Authorization: token }"
:show-file-list="false"
:on-success="handleUploadSuccess"
>
<el-button type="primary">上传文件</el-button>
</el-upload>
</template>
<script setup lang="ts">
const handleUploadSuccess = (res: any) => {
if (res.code === '00000') {
console.log('文件地址:', res.data.url);
}
};
</script>统一要求
- 参数名必须为
file - Header 需携带
Authorization: Bearer {token} - 只依赖
data.url,不关心存储类型
相关文件
| 文件 | 说明 |
|---|---|
Youlai.Api/Controllers/FilesController.cs | 文件上传控制器 |
Youlai.Application/System/Services/IFileService.cs | 文件服务接口 |
Youlai.Infrastructure/Services/LocalFileService.cs | 本地存储实现 |
