Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(storage): implement local storage provider with upload and retrieval functionality

cuijianzhuangd69883d340ad
diff --git a/.env.example b/.env.example
index 40c5542f..4f618a88 100644
--- a/.env.example
+++ b/.env.example
@@ -1,4 +1,4 @@
-# Admin user email (required)
+# Admin user email (required)
CFRAME_ADMIN_EMAIL=
# Admin user name (default to Chronoframe, optional)
CFRAME_ADMIN_NAME=
@@ -29,6 +29,14 @@ NUXT_PROVIDER_S3_SECRET_ACCESS_KEY=
NUXT_PROVIDER_S3_PREFIX=photos/
NUXT_PROVIDER_S3_CDN_URL=
+# 本地存储路径(绝对路径)
+# Windows 示例:C:\Users\you\WebstormProjects\chronoframe\storage
+# Linux/macOS 示例:/app/storage
+NUXT_PROVIDER_LOCAL_PATH=
+
+# 对外访问前缀(已内置路由 /storage/*)
+NUXT_PROVIDER_LOCAL_BASE_URL=/storage
+
# Session password for encrypting session data, 32 characters long
NUXT_SESSION_PASSWORD=
@@ -43,3 +51,27 @@ NUXT_ALLOW_INSECURE_COOKIE=false
# Google Analytics Measurement ID (e.g. G-XXXXXXX)
NUXT_PUBLIC_GTAG_ID=
+
+# -----------------
+# Upload Configuration
+# -----------------
+# Enable MIME type whitelist validation for file uploads (default: true)
+NUXT_UPLOAD_MIME_WHITELIST_ENABLED=true
+
+# Comma-separated list of allowed MIME types for uploads
+# Default includes: image/jpeg, image/png, image/webp, image/gif, image/bmp,
+# image/tiff, image/heic, image/heif, video/quicktime, video/mp4
+NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4
+
+# To disable whitelist and allow any file type, set:
+# NUXT_UPLOAD_MIME_WHITELIST_ENABLED=false
+
+
+# Enable duplicate file detection during upload (default: true)
+NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED=true
+
+# Duplicate detection mode (default: skip)
+# - 'warn': Show warning but allow upload (will overwrite existing photo)
+# - 'block': Reject upload if file already exists
+# - 'skip': Skip upload and return existing photo info
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
\ No newline at end of file
diff --git a/README.md b/README.md
index bb3a9d98..b703a1c6 100644
--- a/README.md
+++ b/README.md
@@ -42,7 +42,14 @@ A smooth photo display and management application, supporting multiple image for
We recommend deploying with the prebuilt Docker image. [View the image on ghcr](https://github.com/HoshinoSuzumi/chronoframe/pkgs/container/chronoframe)
-Before deployment, create a `.env` file and configure environment variables. Refer to [.env.example](./.env.example).
+Before deployment, create a `.env` file and configure environment variables.
+
+You can copy the example file to get started:
+```bash
+cp env.example .env
+```
+
+Then edit the `.env` file with your configuration. For complete configuration reference, see [env.example](./env.example).
```env
# Admin user email (required)
@@ -81,6 +88,10 @@ NUXT_SESSION_PASSWORD=
NUXT_PUBLIC_OAUTH_GITHUB_ENABLED=false
NUXT_OAUTH_GITHUB_CLIENT_ID=
NUXT_OAUTH_GITHUB_CLIENT_SECRET=
+
+# Upload file type whitelist (optional)
+NUXT_UPLOAD_MIME_WHITELIST_ENABLED=true
+NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4
```
### Docker
diff --git a/README_zh.md b/README_zh.md
index 889c4b2e..1f620051 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -45,7 +45,14 @@
推荐使用预构建的 docker 镜像部署,[在 ghcr 上查看镜像](https://github.com/HoshinoSuzumi/chronoframe/pkgs/container/chronoframe)
-部署前请先创建 `.env` 文件并配置环境变量,参考 [.env.example](./.env.example)。
+部署前请先创建 `.env` 文件并配置环境变量。
+
+你可以复制示例文件开始:
+```bash
+cp env.example .env
+```
+
+然后编辑 `.env` 文件,填入你的配置。完整配置说明请参考 [env.example](./env.example)。
```env
# Admin user email (required)
@@ -83,6 +90,10 @@ NUXT_SESSION_PASSWORD=
# GitHub OAuth
NUXT_OAUTH_GITHUB_CLIENT_ID=
NUXT_OAUTH_GITHUB_CLIENT_SECRET=
+
+# 上传文件类型白名单(可选)
+NUXT_UPLOAD_MIME_WHITELIST_ENABLED=true
+NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4
```
### Docker
diff --git a/app/components/Histogram.vue b/app/components/Histogram.vue
index 331f2c92..4591c881 100644
--- a/app/components/Histogram.vue
+++ b/app/components/Histogram.vue
@@ -42,7 +42,7 @@ watchEffect(() => {
currentImage = img
img.crossOrigin = 'anonymous'
- const url = new URL(props.thumbnailUrl)
+ const url = new URL(props.thumbnailUrl, window.location.origin)
url.searchParams.set('_cors', Date.now().toString())
img.src = url.toString()
diff --git a/app/components/ui/UploadQueueItem.vue b/app/components/ui/UploadQueueItem.vue
index 4a31a8c4..23e1efbe 100644
--- a/app/components/ui/UploadQueueItem.vue
+++ b/app/components/ui/UploadQueueItem.vue
@@ -13,6 +13,8 @@ interface UploadFile {
| 'processing'
| 'completed'
| 'error'
+ | 'skipped'
+ | 'blocked'
stage?: string | null
progress?: number
error?: string
@@ -63,6 +65,10 @@ const statusColor = computed(() => {
return 'success'
case 'error':
return 'error'
+ case 'skipped':
+ return 'warning'
+ case 'blocked':
+ return 'error'
default:
return 'neutral'
}
@@ -84,6 +90,10 @@ const statusText = computed(() => {
return '完成'
case 'error':
return '错误'
+ case 'skipped':
+ return '已跳过'
+ case 'blocked':
+ return '被阻止'
default:
return '未知'
}
@@ -210,6 +220,8 @@ const generateParticleStyle = (index: number) => {
statusColor === 'success',
'bg-red-100 dark:bg-red-900/30 border-red-200 dark:border-red-800/50':
statusColor === 'error',
+ 'bg-yellow-100 dark:bg-yellow-900/30 border-yellow-200 dark:border-yellow-800/50':
+ statusColor === 'warning',
'bg-neutral-100 dark:bg-neutral-900/30 border-neutral-200 dark:border-neutral-800/50':
statusColor === 'neutral',
}"
@@ -223,6 +235,7 @@ const generateParticleStyle = (index: number) => {
'text-green-600/80 dark:text-green-400/80':
statusColor === 'success',
'text-red-600/80 dark:text-red-400/80': statusColor === 'error',
+ 'text-yellow-600/80 dark:text-yellow-400/80': statusColor === 'warning',
'text-neutral-600/80 dark:text-neutral-400/80':
statusColor === 'neutral',
}"
@@ -243,6 +256,34 @@ const generateParticleStyle = (index: number) => {
/>
</motion.div>
+ <!-- 跳过指示器 -->
+ <motion.div
+ v-if="uploadingFile.status === 'skipped'"
+ class="absolute -top-2 -right-2 size-5 bg-yellow-600 rounded-full border-2 border-white dark:border-neutral-800 flex items-center justify-center"
+ :initial="{ scale: 0 }"
+ :animate="{ scale: 1 }"
+ :transition="{ delay: 0.2, duration: 0.3, ease: 'backOut' }"
+ >
+ <Icon
+ name="tabler:arrow-right"
+ class="size-3 text-white"
+ />
+ </motion.div>
+
+ <!-- 阻止指示器 -->
+ <motion.div
+ v-if="uploadingFile.status === 'blocked'"
+ class="absolute -top-2 -right-2 size-5 bg-red-600 rounded-full border-2 border-white dark:border-neutral-800 flex items-center justify-center"
+ :initial="{ scale: 0 }"
+ :animate="{ scale: 1 }"
+ :transition="{ delay: 0.2, duration: 0.3, ease: 'backOut' }"
+ >
+ <Icon
+ name="tabler:x"
+ class="size-3 text-white"
+ />
+ </motion.div>
+
<!-- 完成粒子动画 -->
<AnimatePresence>
<motion.div
diff --git a/app/components/ui/UploadQueuePanel.vue b/app/components/ui/UploadQueuePanel.vue
index f2df4917..f70a5fc5 100644
--- a/app/components/ui/UploadQueuePanel.vue
+++ b/app/components/ui/UploadQueuePanel.vue
@@ -12,6 +12,8 @@ interface UploadFile {
| 'processing'
| 'completed'
| 'error'
+ | 'skipped'
+ | 'blocked'
stage?: string | null
progress?: number
error?: string
@@ -54,6 +56,8 @@ const stats = computed(() => {
processing: files.filter((f) => f.status === 'processing').length,
completed: files.filter((f) => f.status === 'completed').length,
error: files.filter((f) => f.status === 'error').length,
+ skipped: files.filter((f) => f.status === 'skipped').length,
+ blocked: files.filter((f) => f.status === 'blocked').length,
active: files.filter(
(f) => f.status === 'uploading' || f.status === 'processing',
).length,
@@ -85,6 +89,9 @@ const overallProgress = computed(() => {
} else if (file.status === 'waiting') {
// 等待状态:0%
totalProgress += 0
+ } else if (file.status === 'skipped' || file.status === 'blocked') {
+ // 跳过或被阻止:0%(不参与进度计算)
+ totalProgress += 0
}
})
@@ -93,8 +100,9 @@ const overallProgress = computed(() => {
// 计算状态颜色
const statusColor = computed(() => {
- if (stats.value.error > 0) return 'error'
+ if (stats.value.error > 0 || stats.value.blocked > 0) return 'error'
if (stats.value.active > 0) return 'primary'
+ if (stats.value.skipped > 0 && stats.value.active === 0) return 'warning'
if (stats.value.completed > 0 && stats.value.active === 0) return 'success'
return 'neutral'
})
@@ -147,6 +155,7 @@ const clearAllFiles = () => {
primary: 'tabler:upload',
success: 'tabler:circle-check',
error: 'tabler:alert-circle',
+ warning: 'tabler:alert-triangle',
neutral: 'tabler:info-circle',
}[statusColor]
"
@@ -155,6 +164,7 @@ const clearAllFiles = () => {
'text-blue-600 dark:text-blue-400': statusColor === 'primary',
'text-green-600 dark:text-green-400': statusColor === 'success',
'text-red-600 dark:text-red-400': statusColor === 'error',
+ 'text-yellow-600 dark:text-yellow-400': statusColor === 'warning',
'text-neutral-600 dark:text-neutral-400':
statusColor === 'neutral',
}"
@@ -198,6 +208,18 @@ const clearAllFiles = () => {
>
{{ stats.error }} 失败
</span>
+ <span
+ v-if="stats.skipped > 0"
+ class="text-yellow-600 dark:text-yellow-400"
+ >
+ {{ stats.skipped }} 跳过
+ </span>
+ <span
+ v-if="stats.blocked > 0"
+ class="text-red-600 dark:text-red-400"
+ >
+ {{ stats.blocked }} 被阻止
+ </span>
</div>
</div>
</div>
diff --git a/app/composables/useUpload.ts b/app/composables/useUpload.ts
index 62518a28..616e5008 100644
--- a/app/composables/useUpload.ts
+++ b/app/composables/useUpload.ts
@@ -20,6 +20,7 @@ export interface UploadCallbacks {
onSuccess?: (response: XMLHttpRequest) => void
onError?: (error: string, xhr: XMLHttpRequest) => void
onAbort?: () => void
+ onRetry?: (attempt: number, maxAttempts: number) => void
}
export interface UseUploadOptions {
@@ -27,6 +28,8 @@ export interface UseUploadOptions {
withCredentials?: boolean
headers?: Record<string, string>
speedSampleSize?: number // 用于计算速度的样本数量
+ maxRetries?: number // 最大重试次数
+ retryDelay?: number // 重试延迟(毫秒)
}
export function useUpload(options: UseUploadOptions = {}) {
@@ -34,7 +37,9 @@ export function useUpload(options: UseUploadOptions = {}) {
timeout = 0,
withCredentials = false,
headers = {},
- speedSampleSize = 5
+ speedSampleSize = 5,
+ maxRetries = 3,
+ retryDelay = 1000
} = options
// 响应式状态
@@ -129,10 +134,13 @@ export function useUpload(options: UseUploadOptions = {}) {
const uploadFile = async (
file: File,
signedUrl: string,
- callbacks: UploadCallbacks = {}
+ callbacks: UploadCallbacks = {},
+ attempt: number = 1
): Promise<XMLHttpRequest> => {
- // 重置状态
- resetStatus()
+ // 重置状态(仅在第一次尝试时)
+ if (attempt === 1) {
+ resetStatus()
+ }
return new Promise((resolve, reject) => {
// 创建新的 XHR 实例
@@ -172,21 +180,82 @@ export function useUpload(options: UseUploadOptions = {}) {
// 错误处理
xhr.addEventListener('error', () => {
const endTime = Date.now()
- const error = `网络错误 (状态码: ${xhr.status})`
- updateStatus({ status: 'error', error, endTime })
- callbacks.onStatusChange?.('error')
- callbacks.onError?.(error, xhr)
- reject(new Error(error))
+ let errorMessage = ''
+ let suggestion = ''
+
+ if (xhr.status === 0) {
+ // 状态码 0 通常表示网络连接失败、CORS 问题或服务器不可达
+ errorMessage = '网络连接失败'
+ suggestion = '请检查网络连接或稍后重试。如果问题持续存在,可能是服务器配置问题。'
+ } else if (xhr.status >= 400 && xhr.status < 500) {
+ errorMessage = `客户端错误 (${xhr.status})`
+ suggestion = '请检查文件格式和大小是否符合要求。'
+ } else if (xhr.status >= 500) {
+ errorMessage = `服务器错误 (${xhr.status})`
+ suggestion = '服务器暂时不可用,请稍后重试。'
+ } else {
+ errorMessage = `网络错误 (状态码: ${xhr.status})`
+ suggestion = '请检查网络连接后重试。'
+ }
+
+ // 检查是否可以重试
+ const canRetry = attempt < maxRetries && (
+ xhr.status === 0 || // 网络错误
+ xhr.status >= 500 || // 服务器错误
+ xhr.status === 429 // 频率限制
+ )
+
+ if (canRetry) {
+ updateStatus({
+ status: 'error',
+ error: `${errorMessage} (尝试 ${attempt}/${maxRetries})`,
+ endTime
+ })
+ callbacks.onRetry?.(attempt, maxRetries)
+
+ // 延迟后重试
+ setTimeout(() => {
+ uploadFile(file, signedUrl, callbacks, attempt + 1)
+ .then(resolve)
+ .catch(reject)
+ }, retryDelay * attempt) // 指数退避
+ } else {
+ updateStatus({ status: 'error', error: errorMessage, endTime })
+ callbacks.onStatusChange?.('error')
+ callbacks.onError?.(errorMessage, xhr)
+ reject(new Error(errorMessage))
+ }
})
// 超时处理
xhr.addEventListener('timeout', () => {
const endTime = Date.now()
- const error = `上传超时 (${timeout}ms)`
- updateStatus({ status: 'error', error, endTime })
- callbacks.onStatusChange?.('error')
- callbacks.onError?.(error, xhr)
- reject(new Error(error))
+ const errorMessage = `上传超时 (${timeout}ms)`
+ const suggestion = '文件可能过大或网络较慢,请尝试:1) 检查网络连接;2) 稍后重试;3) 尝试上传较小的文件。'
+
+ // 检查是否可以重试(超时也可以重试)
+ const canRetry = attempt < maxRetries
+
+ if (canRetry) {
+ updateStatus({
+ status: 'error',
+ error: `${errorMessage} (尝试 ${attempt}/${maxRetries})`,
+ endTime
+ })
+ callbacks.onRetry?.(attempt, maxRetries)
+
+ // 延迟后重试
+ setTimeout(() => {
+ uploadFile(file, signedUrl, callbacks, attempt + 1)
+ .then(resolve)
+ .catch(reject)
+ }, retryDelay * attempt) // 指数退避
+ } else {
+ updateStatus({ status: 'error', error: errorMessage, endTime })
+ callbacks.onStatusChange?.('error')
+ callbacks.onError?.(errorMessage, xhr)
+ reject(new Error(errorMessage))
+ }
})
// 中止处理
@@ -206,21 +275,80 @@ export function useUpload(options: UseUploadOptions = {}) {
return
} else if (xhr.status >= 400) {
const endTime = Date.now()
- let error = `HTTP 错误: ${xhr.status}`
+ let errorMessage = ''
+ let suggestion = ''
- // 尝试获取更详细的错误信息
+ // 根据状态码提供更友好的错误信息
+ switch (xhr.status) {
+ case 400:
+ errorMessage = '请求格式错误'
+ suggestion = '请检查文件格式是否正确。'
+ break
+ case 401:
+ errorMessage = '未授权访问'
+ suggestion = '请重新登录后再试。'
+ break
+ case 403:
+ errorMessage = '访问被拒绝'
+ suggestion = '您没有权限执行此操作。'
+ break
+ case 404:
+ errorMessage = '上传接口不存在'
+ suggestion = '请检查应用配置或联系管理员。'
+ break
+ case 409:
+ errorMessage = '文件冲突'
+ suggestion = '文件已存在,请重命名后重新上传。'
+ break
+ case 413:
+ errorMessage = '文件过大'
+ suggestion = '请选择更小的文件(建议小于 128MB)。'
+ break
+ case 415:
+ errorMessage = '不支持的文件类型'
+ suggestion = '请上传支持的文件格式(JPEG、PNG、HEIC、MOV)。'
+ break
+ case 429:
+ errorMessage = '上传频率过高'
+ suggestion = '请稍等片刻后再试。'
+ break
+ case 500:
+ errorMessage = '服务器内部错误'
+ suggestion = '服务器暂时出现问题,请稍后重试。'
+ break
+ case 502:
+ case 503:
+ case 504:
+ errorMessage = '服务器暂时不可用'
+ suggestion = '服务器正在维护中,请稍后重试。'
+ break
+ default:
+ errorMessage = `HTTP 错误: ${xhr.status}`
+ suggestion = '请检查网络连接后重试。'
+ }
+
+ // 尝试获取服务器返回的详细错误信息
try {
const responseText = xhr.responseText
if (responseText) {
- error += ` - ${responseText}`
+ try {
+ const responseData = JSON.parse(responseText)
+ if (responseData.data?.message) {
+ errorMessage = responseData.data.title || errorMessage
+ suggestion = responseData.data.suggestion || suggestion
+ }
+ } catch {
+ // 如果不是 JSON,使用原始文本
+ errorMessage += ` - ${responseText}`
+ }
}
} catch {
// 忽略解析错误
}
- updateStatus({ status: 'error', error, endTime })
+ updateStatus({ status: 'error', error: errorMessage, endTime })
callbacks.onStatusChange?.('error')
- callbacks.onError?.(error, xhr)
+ callbacks.onError?.(errorMessage, xhr)
}
}
})
@@ -295,11 +423,15 @@ export function useUpload(options: UseUploadOptions = {}) {
}
})
- // 清理函数
- onUnmounted(() => {
- abortUpload()
- currentXHR = null
- })
+ // 清理函数(仅在组件上下文中可用)
+ try {
+ onUnmounted(() => {
+ abortUpload()
+ currentXHR = null
+ })
+ } catch {
+ // 忽略在非组件 setup 上下文中调用时的生命周期注册
+ }
return {
// 状态
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index 92d17319..f544abac 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -61,6 +61,8 @@ interface UploadingFile {
| 'processing'
| 'completed'
| 'error'
+ | 'skipped'
+ | 'blocked'
stage?: PipelineQueueItem['statusStage'] | null
progress?: number
error?: string
@@ -121,6 +123,33 @@ const uploadImage = async (file: File, existingFileId?: string) => {
})
uploadingFile.signedUrlResponse = signedUrlResponse
+
+ // 检查是否为跳过模式(重复文件)
+ if (signedUrlResponse.skipped) {
+ uploadingFile.status = 'skipped'
+ uploadingFile.progress = 100
+ uploadingFile.canAbort = false
+ uploadingFiles.value = new Map(uploadingFiles.value)
+
+ // 显示跳过信息
+ toast.add({
+ title: signedUrlResponse.title || '文件已存在',
+ description: signedUrlResponse.message || '文件已存在,已自动跳过上传',
+ color: 'warning',
+ })
+ return
+ }
+
+ // 检查是否为警告模式(重复文件但继续上传)
+ if (signedUrlResponse.duplicate && signedUrlResponse.warningInfo) {
+ toast.add({
+ title: signedUrlResponse.warningInfo.title || '检测到重复文件',
+ description: signedUrlResponse.warningInfo.message || '文件已存在,继续上传将会覆盖现有照片',
+ color: 'warning',
+ timeout: 8000,
+ })
+ }
+
uploadingFile.status = 'uploading'
uploadingFile.canAbort = true
uploadingFile.progress = 0
@@ -202,8 +231,42 @@ const uploadImage = async (file: File, existingFileId?: string) => {
})
} catch (error: any) {
uploadingFile.status = 'error'
- uploadingFile.error = error.message || '上传失败'
uploadingFile.canAbort = false
+
+ // 处理重复文件阻止模式的错误
+ if (error.statusCode === 409 && error.data?.duplicate) {
+ uploadingFile.status = 'blocked'
+ uploadingFile.error = error.data.title || '文件已存在'
+
+ // 显示详细的错误信息
+ toast.add({
+ title: error.data.title || '文件已存在',
+ description: error.data.message || '无法上传重复文件',
+ color: 'error',
+ timeout: 10000,
+ })
+
+ // 如果有建议信息,也显示
+ if (error.data.suggestion) {
+ setTimeout(() => {
+ toast.add({
+ title: '解决建议',
+ description: error.data.suggestion,
+ color: 'info',
+ timeout: 8000,
+ })
+ }, 1000)
+ }
+ } else {
+ // 其他错误
+ uploadingFile.error = error.message || '上传失败'
+ toast.add({
+ title: '上传失败',
+ description: error.message || '上传过程中发生错误',
+ color: 'error',
+ })
+ }
+
uploadingFiles.value = new Map(uploadingFiles.value)
// 提供更详细的错误信息
diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md
index 4428c66a..edcb6ad1 100644
--- a/docs/guide/configuration.md
+++ b/docs/guide/configuration.md
@@ -28,3 +28,76 @@ Whether using Docker or Docker Compose (.env) deployment, configuration is done
| NUXT_OAUTH_GITHUB_CLIENT_SECRET | GitHub OAuth app Client Secret | None | No (optional, for GitHub login) |
| NUXT_SESSION_PASSWORD | Password for encrypting sessions, 32-character random string | None | Yes |
| NUXT_PUBLIC_GTAG_ID | Google Analytics Tracking ID | None | No |
+| NUXT_UPLOAD_MIME_WHITELIST_ENABLED | Enable MIME type whitelist validation for uploads | true | No |
+| NUXT_UPLOAD_MIME_WHITELIST | Allowed MIME types for uploads (comma-separated) | See below | No |
+| NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED | Enable duplicate file detection during upload | true | No |
+| NUXT_UPLOAD_DUPLICATE_CHECK_MODE | Duplicate handling mode: warn/block/skip | warn | No |
+
+## Upload File Type Whitelist
+
+The default value of `NUXT_UPLOAD_MIME_WHITELIST` includes the following MIME types:
+- `image/jpeg` - JPEG images
+- `image/png` - PNG images
+- `image/webp` - WebP images
+- `image/gif` - GIF images
+- `image/bmp` - BMP images
+- `image/tiff` - TIFF images
+- `image/heic` - HEIC images (Apple)
+- `image/heif` - HEIF images
+- `video/quicktime` - QuickTime videos (MOV)
+- `video/mp4` - MP4 videos
+
+To customize the whitelist, use a comma-separated string of MIME types, for example:
+```
+NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,video/mp4
+```
+
+To disable whitelist validation (allow any file type), set:
+```
+NUXT_UPLOAD_MIME_WHITELIST_ENABLED=false
+```
+
+## Duplicate File Detection
+
+`NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED` controls whether to detect duplicate files during upload.
+
+`NUXT_UPLOAD_DUPLICATE_CHECK_MODE` has three modes:
+
+### warn (Warning Mode) - Default
+- Shows warning when duplicate file is detected
+- Continues upload, will overwrite existing photo data
+- Suitable for scenarios where photo updates are needed
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=warn
+```
+
+### block (Block Mode)
+- Rejects upload if duplicate file is detected
+- Returns 409 error, doesn't allow overwriting
+- Suitable for scenarios requiring strict duplicate prevention
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=block
+```
+
+### skip (Skip Mode)
+- Skips upload when duplicate file is detected
+- Returns existing photo info without any operations
+- Suitable for automatic deduplication during batch uploads
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
+```
+
+### Completely Disable Detection
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED=false
+```
+
+**Notes**:
+- Duplicate detection is based on filename, not file content
+- Same filename generates same photoId
+- Even with detection disabled, uploading same filename will still overwrite existing data (database uses `onConflictDoUpdate`)
+- Recommend using unique filenames (e.g., adding timestamps) to avoid conflicts
diff --git a/docs/zh/guide/configuration.md b/docs/zh/guide/configuration.md
index 18290e02..fd44c814 100644
--- a/docs/zh/guide/configuration.md
+++ b/docs/zh/guide/configuration.md
@@ -28,3 +28,76 @@
| NUXT_OAUTH_GITHUB_CLIENT_SECRET | GitHub OAuth 应用的 Client Secret | 无 | 否(可选,用于 GitHub 登录) |
| NUXT_SESSION_PASSWORD | 用于加密会话的密码,32 位随机字符串 | 无 | 是 |
| NUXT_PUBLIC_GTAG_ID | Google Analytics 追踪 ID | 无 | 否 |
+| NUXT_UPLOAD_MIME_WHITELIST_ENABLED | 是否启用上传文件 MIME 类型白名单验证 | true | 否 |
+| NUXT_UPLOAD_MIME_WHITELIST | 上传文件允许的 MIME 类型列表(逗号分隔) | 见下方说明 | 否 |
+| NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED | 是否启用重复文件检测 | true | 否 |
+| NUXT_UPLOAD_DUPLICATE_CHECK_MODE | 重复文件处理模式:warn/block/skip | warn | 否 |
+
+## 上传文件类型白名单
+
+`NUXT_UPLOAD_MIME_WHITELIST` 的默认值包含以下 MIME 类型:
+- `image/jpeg` - JPEG 图片
+- `image/png` - PNG 图片
+- `image/webp` - WebP 图片
+- `image/gif` - GIF 图片
+- `image/bmp` - BMP 图片
+- `image/tiff` - TIFF 图片
+- `image/heic` - HEIC 图片(Apple)
+- `image/heif` - HEIF 图片
+- `video/quicktime` - QuickTime 视频(MOV)
+- `video/mp4` - MP4 视频
+
+如需自定义白名单,请使用逗号分隔的 MIME 类型字符串,例如:
+```
+NUXT_UPLOAD_MIME_WHITELIST=image/jpeg,image/png,video/mp4
+```
+
+如需禁用白名单验证(允许任何文件类型),可设置:
+```
+NUXT_UPLOAD_MIME_WHITELIST_ENABLED=false
+```
+
+## 重复文件检测
+
+`NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED` 控制是否在上传时检测重复文件。
+
+`NUXT_UPLOAD_DUPLICATE_CHECK_MODE` 有三种模式:
+
+### warn(警告模式)- 默认
+- 检测到重复文件时显示警告
+- 继续上传,会覆盖现有照片数据
+- 适合需要更新照片的场景
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=warn
+```
+
+### block(阻止模式)
+- 检测到重复文件时拒绝上传
+- 返回 409 错误,不允许覆盖
+- 适合严格防止重复的场景
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=block
+```
+
+### skip(跳过模式)
+- 检测到重复文件时跳过上传
+- 返回现有照片信息,不进行任何操作
+- 适合批量上传时自动去重
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_MODE=skip
+```
+
+### 完全禁用检测
+
+```
+NUXT_UPLOAD_DUPLICATE_CHECK_ENABLED=false
+```
+
+**注意事项**:
+- 重复检测基于文件名,不基于文件内容
+- 相同文件名会生成相同的 photoId
+- 即使禁用检测,上传同名文件仍会覆盖现有数据(数据库使用 `onConflictDoUpdate`)
+- 建议使用唯一的文件名(如添加时间戳)来避免冲突
diff --git a/nuxt.config.ts b/nuxt.config.ts
index 6a027f83..863818d7 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -51,6 +51,12 @@ export default defineNuxtConfig({
PROVIDER_S3_PREFIX: '',
PROVIDER_S3_CDN_URL: '',
ALLOW_INSECURE_COOKIE: false,
+ // 上传文件类型白名单配置
+ UPLOAD_MIME_WHITELIST_ENABLED: true,
+ UPLOAD_MIME_WHITELIST: 'image/jpeg,image/png,image/webp,image/gif,image/bmp,image/tiff,image/heic,image/heif,video/quicktime,video/mp4',
+ // 重复文件检测配置
+ UPLOAD_DUPLICATE_CHECK_ENABLED: true,
+ UPLOAD_DUPLICATE_CHECK_MODE: 'warn', // 'warn' | 'block' | 'skip'
},
nitro: {
diff --git a/packages/webgl-image/src/core/WebGLImageViewerEngine.ts b/packages/webgl-image/src/core/WebGLImageViewerEngine.ts
index 956c7a9e..36c03641 100644
--- a/packages/webgl-image/src/core/WebGLImageViewerEngine.ts
+++ b/packages/webgl-image/src/core/WebGLImageViewerEngine.ts
@@ -326,7 +326,12 @@ export class WebGLImageViewerEngine {
this.imageLoadingResolve = resolve
this.imageLoadingReject = reject
if (this.worker) {
- this.worker.postMessage({ type: 'load', payload: { src } })
+ try {
+ const absolute = new URL(src, self.location?.origin || 'http://localhost')
+ this.worker.postMessage({ type: 'load', payload: { src: absolute.toString() } })
+ } catch {
+ this.worker.postMessage({ type: 'load', payload: { src } })
+ }
} else {
reject(new Error('No worker available'))
}
diff --git a/packages/webgl-image/src/workers/image-decoder.worker.js b/packages/webgl-image/src/workers/image-decoder.worker.js
index a74d2755..f14cd650 100644
--- a/packages/webgl-image/src/workers/image-decoder.worker.js
+++ b/packages/webgl-image/src/workers/image-decoder.worker.js
@@ -12,7 +12,12 @@ self.onmessage = async (event) => {
if (type === 'load') {
const { payload } = event.data
try {
- const response = await fetch(payload.src, { mode: 'cors' })
+ let src = payload.src
+ try {
+ const absolute = new URL(src, self.location?.origin || 'http://localhost')
+ src = absolute.toString()
+ } catch {}
+ const response = await fetch(src, { mode: 'cors' })
if (!response.ok) {
throw new Error(`Failed to fetch image: ${response.status}`)
}
diff --git a/server/api/photos/check-duplicate.post.ts b/server/api/photos/check-duplicate.post.ts
new file mode 100644
index 00000000..6b665ec1
--- /dev/null
+++ b/server/api/photos/check-duplicate.post.ts
@@ -0,0 +1,128 @@
+import { z } from 'zod'
+import { eq } from 'drizzle-orm'
+import { generateSafePhotoId } from '~~/server/utils/file-utils'
+import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-messages'
+
+/**
+ * 检查照片是否已存在
+ * 可以检查单个或多个文件
+ */
+export default defineEventHandler(async (event) => {
+ await requireUserSession(event)
+
+ const lang = getPreferredLanguage(event)
+
+ try {
+ const { fileNames, storageKeys } = await readValidatedBody(
+ event,
+ z.object({
+ fileNames: z.array(z.string()).optional(),
+ storageKeys: z.array(z.string()).optional(),
+ }).parse,
+ )
+
+ if (!fileNames && !storageKeys) {
+ const errorMsg = getMessage('error', 'required', lang, 'fileNames or storageKeys')
+ throw createError({
+ statusCode: 400,
+ statusMessage: errorMsg?.title || 'Missing required parameter',
+ data: errorMsg,
+ })
+ }
+
+ const db = useDB()
+ const results = []
+
+ // 检查文件名
+ if (fileNames && fileNames.length > 0) {
+ for (const fileName of fileNames) {
+ // 生成 photoId(与上传时的逻辑相同)
+ const { storageProvider } = useStorageProvider(event)
+ const storageKey = `${(storageProvider.config?.prefix || '').replace(/\/+$/, '')}/${fileName}`
+ const photoId = generateSafePhotoId(storageKey)
+
+ // 查询数据库
+ const existingPhoto = await db
+ .select({
+ id: tables.photos.id,
+ title: tables.photos.title,
+ storageKey: tables.photos.storageKey,
+ originalUrl: tables.photos.originalUrl,
+ thumbnailUrl: tables.photos.thumbnailUrl,
+ dateTaken: tables.photos.dateTaken,
+ fileSize: tables.photos.fileSize,
+ width: tables.photos.width,
+ height: tables.photos.height,
+ })
+ .from(tables.photos)
+ .where(eq(tables.photos.id, photoId))
+ .get()
+
+ results.push({
+ fileName,
+ storageKey,
+ photoId,
+ exists: !!existingPhoto,
+ photo: existingPhoto || null,
+ })
+ }
+ }
+
+ // 检查 storageKey
+ if (storageKeys && storageKeys.length > 0) {
+ for (const storageKey of storageKeys) {
+ const photoId = generateSafePhotoId(storageKey)
+
+ const existingPhoto = await db
+ .select({
+ id: tables.photos.id,
+ title: tables.photos.title,
+ storageKey: tables.photos.storageKey,
+ originalUrl: tables.photos.originalUrl,
+ thumbnailUrl: tables.photos.thumbnailUrl,
+ dateTaken: tables.photos.dateTaken,
+ fileSize: tables.photos.fileSize,
+ width: tables.photos.width,
+ height: tables.photos.height,
+ })
+ .from(tables.photos)
+ .where(eq(tables.photos.id, photoId))
+ .get()
+
+ results.push({
+ storageKey,
+ photoId,
+ exists: !!existingPhoto,
+ photo: existingPhoto || null,
+ })
+ }
+ }
+
+ const duplicatesFound = results.filter(r => r.exists).length
+ const successMsg = getMessage('success', 'check', lang, results.length, duplicatesFound)
+
+ return {
+ success: true,
+ results,
+ duplicatesFound,
+ summary: successMsg || {
+ title: lang === 'zh' ? '检查完成' : 'Check Complete',
+ message: lang === 'zh'
+ ? `已检查 ${results.length} 个文件,发现 ${duplicatesFound} 个重复文件`
+ : `Checked ${results.length} files, found ${duplicatesFound} duplicates`,
+ },
+ }
+ } catch (error: any) {
+ if (error.statusCode) {
+ throw error
+ }
+
+ const errorMsg = getMessage('error', 'uploadFailed', lang, error.message)
+ throw createError({
+ statusCode: 500,
+ statusMessage: errorMsg?.title || 'Failed to check duplicates',
+ data: errorMsg,
+ })
+ }
+})
+
diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts
index 57cf1d41..2f7c5e82 100644
--- a/server/api/photos/index.post.ts
+++ b/server/api/photos/index.post.ts
@@ -1,50 +1,131 @@
import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+import { eq } from 'drizzle-orm'
+import { generateSafePhotoId } from '~~/server/utils/file-utils'
+import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-messages'
export default eventHandler(async (event) => {
await requireUserSession(event)
-
const { storageProvider } = useStorageProvider(event)
-
- // 检查存储提供商是否支持预签名 URL
- if (!storageProvider.getSignedUrl) {
- throw createError({
- statusCode: 501,
- statusMessage: 'Storage provider does not support signed URLs',
- })
- }
+ const lang = getPreferredLanguage(event)
const body = await readBody(event)
- const { fileName, contentType } = body
+ const { fileName, contentType, skipDuplicateCheck } = body
if (!fileName) {
+ const errorMsg = getMessage('error', 'required', lang, 'fileName')
throw createError({
statusCode: 400,
- statusMessage: 'fileName is required',
+ statusMessage: errorMsg?.title || 'Missing required parameter',
+ data: errorMsg,
})
}
try {
const objectKey = `${(storageProvider.config?.prefix || '').replace(/\/+$/, '')}/${fileName}`
+ const config = useRuntimeConfig(event)
+
+ // 重复文件检测
+ const duplicateCheckEnabled = config.UPLOAD_DUPLICATE_CHECK_ENABLED && !skipDuplicateCheck
+ let existingPhoto = null
+
+ if (duplicateCheckEnabled) {
+ const photoId = generateSafePhotoId(objectKey)
+ const db = useDB()
+
+ existingPhoto = await db
+ .select({
+ id: tables.photos.id,
+ title: tables.photos.title,
+ storageKey: tables.photos.storageKey,
+ originalUrl: tables.photos.originalUrl,
+ thumbnailUrl: tables.photos.thumbnailUrl,
+ dateTaken: tables.photos.dateTaken,
+ })
+ .from(tables.photos)
+ .where(eq(tables.photos.id, photoId))
+ .get()
+
+ if (existingPhoto) {
+ const checkMode = config.UPLOAD_DUPLICATE_CHECK_MODE || 'warn'
+
+ if (checkMode === 'block') {
+ // 阻止模式:直接拒绝上传
+ const blockMsg = getMessage('duplicate', 'block', lang, fileName)
+ throw createError({
+ statusCode: 409,
+ statusMessage: blockMsg?.title || 'File already exists',
+ data: {
+ duplicate: true,
+ existingPhoto,
+ ...blockMsg,
+ },
+ })
+ } else if (checkMode === 'skip') {
+ // 跳过模式:返回现有照片信息,不上传
+ const skipMsg = getMessage('duplicate', 'skip', lang, fileName, existingPhoto)
+ return {
+ skipped: true,
+ duplicate: true,
+ existingPhoto,
+ fileKey: objectKey,
+ ...skipMsg,
+ }
+ }
+ // 'warn' 模式:继续上传但返回警告信息
+ }
+ }
+
+ // 若存储提供商支持预签名 URL,返回外部直传地址
+ if (storageProvider.getSignedUrl) {
+ const signedUrl = await storageProvider.getSignedUrl(
+ objectKey,
+ 3600,
+ {
+ contentType: contentType || 'application/octet-stream',
+ },
+ )
- // 获取预签名 URL,设置1小时过期时间
- const signedUrl = await storageProvider.getSignedUrl(
- objectKey,
- 3600, // 1小时过期
- {
- contentType: contentType || 'application/octet-stream',
+ const response: any = {
+ signedUrl,
+ fileKey: objectKey,
+ expiresIn: 3600,
}
- )
- return {
- signedUrl,
+ if (existingPhoto) {
+ const warnMsg = getMessage('duplicate', 'warn', lang, fileName, existingPhoto)
+ response.duplicate = true
+ response.existingPhoto = existingPhoto
+ if (warnMsg) {
+ response.warningInfo = warnMsg
+ }
+ }
+
+ return response
+ }
+
+ // 否则回退到内部直传端点(需会话)
+ const internalUploadUrl = `/api/photos/upload?key=${encodeURIComponent(objectKey)}`
+ const response: any = {
+ signedUrl: internalUploadUrl,
fileKey: objectKey,
expiresIn: 3600,
}
+
+ if (existingPhoto) {
+ const warnMsg = getMessage('duplicate', 'warn', lang, fileName, existingPhoto)
+ response.duplicate = true
+ response.existingPhoto = existingPhoto
+ if (warnMsg) {
+ response.warningInfo = warnMsg
+ }
+ }
+
+ return response
} catch (error) {
- logger.chrono.error('Failed to generate signed URL:', error)
- throw createError({
- statusCode: 500,
- statusMessage: 'Failed to generate signed URL',
- })
+ if ((error as any).statusCode) {
+ throw error
+ }
+ logger.chrono.error('Failed to prepare upload:', error)
+ throw createError({ statusCode: 500, statusMessage: 'Failed to prepare upload' })
}
})
\ No newline at end of file
diff --git a/server/api/photos/upload.put.ts b/server/api/photos/upload.put.ts
new file mode 100644
index 00000000..04cecb7c
--- /dev/null
+++ b/server/api/photos/upload.put.ts
@@ -0,0 +1,67 @@
+import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+import { getMessage, getPreferredLanguage } from '~~/server/utils/upload-messages'
+
+export default eventHandler(async (event) => {
+ await requireUserSession(event)
+
+ const { storageProvider } = useStorageProvider(event)
+ const key = getQuery(event).key as string | undefined
+ const lang = getPreferredLanguage(event)
+
+ if (!key) {
+ const errorMsg = getMessage('error', 'required', lang, 'key')
+ throw createError({
+ statusCode: 400,
+ statusMessage: errorMsg?.title || 'Missing required parameter',
+ data: errorMsg,
+ })
+ }
+
+ const contentType = getHeader(event, 'content-type') || 'application/octet-stream'
+
+ // MIME 类型白名单验证(可通过环境变量配置)
+ const config = useRuntimeConfig(event)
+ const whitelistEnabled = config.UPLOAD_MIME_WHITELIST_ENABLED
+
+ if (whitelistEnabled) {
+ const whitelistStr = config.UPLOAD_MIME_WHITELIST
+ const allowedTypes = whitelistStr
+ ? whitelistStr.split(',').map((type: string) => type.trim()).filter(Boolean)
+ : []
+
+ if (allowedTypes.length > 0 && !allowedTypes.includes(contentType)) {
+ const errorMsg = getMessage('error', 'invalidType', lang, contentType, allowedTypes)
+ throw createError({
+ statusCode: 415,
+ statusMessage: errorMsg?.title || 'Unsupported media type',
+ data: errorMsg,
+ })
+ }
+ }
+
+ const raw = await readRawBody(event, false)
+ if (!raw || !(raw instanceof Buffer)) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: lang === 'zh' ? '请求体为空' : 'Empty request body',
+ })
+ }
+
+ // 简单大小限制(例如 128MB)
+ const maxBytes = 128 * 1024 * 1024
+ if (raw.byteLength > maxBytes) {
+ const errorMsg = getMessage('error', 'tooLarge', lang, raw.byteLength, 128)
+ throw createError({
+ statusCode: 413,
+ statusMessage: errorMsg?.title || 'Payload too large',
+ data: errorMsg,
+ })
+ }
+
+ const buffer = raw
+ await storageProvider.create(key.replace(/^\/+/, ''), buffer, contentType)
+
+ return { ok: true, key }
+})
+
+
diff --git a/server/plugins/storage.ts b/server/plugins/storage.ts
index abf5e809..e3dfd440 100644
--- a/server/plugins/storage.ts
+++ b/server/plugins/storage.ts
@@ -1,5 +1,7 @@
+import path from 'node:path'
import type { StorageConfig } from '../services/storage'
import { StorageManager } from '../services/storage'
+import { logger } from '../utils/logger'
// 全局 storageManager 实例,可以在非请求上下文中使用
let globalStorageManager: StorageManager
@@ -14,9 +16,9 @@ export function getStorageManager(): StorageManager {
export default nitroPlugin(async (nitroApp) => {
const config = useRuntimeConfig()
- const devConfigs: Record<'s3' | 'r2', StorageConfig> = {
+ const devConfigs: Record<'s3' | 'r2' | 'local', StorageConfig> = {
s3: {
- provider: (config.STORAGE_PROVIDER as StorageConfig['provider']) || 's3',
+ provider: 's3',
bucket: config.PROVIDER_S3_BUCKET,
region: config.PROVIDER_S3_REGION,
endpoint: config.PROVIDER_S3_ENDPOINT,
@@ -33,9 +35,19 @@ export default nitroPlugin(async (nitroApp) => {
: 'https://cdn-dev.lens.bh8.ga/',
maxKeys: 100,
},
+ local: {
+ provider: 'local',
+ basePath: process.env.NUXT_PROVIDER_LOCAL_PATH || path.resolve(process.cwd(), 'storage'),
+ baseUrl: process.env.NUXT_PROVIDER_LOCAL_BASE_URL || '/storage',
+ prefix: 'photos/',
+ },
}
- const storageManager = new StorageManager(devConfigs.s3, logger.storage)
+ const selectedProvider = (config.STORAGE_PROVIDER as 's3' | 'r2' | 'local') || 's3'
+ const storageManager = new StorageManager(
+ devConfigs[selectedProvider],
+ logger.storage,
+ )
// 设置全局实例
globalStorageManager = storageManager
@@ -43,4 +55,21 @@ export default nitroPlugin(async (nitroApp) => {
nitroApp.hooks.hook('request', (event) => {
event.context.storage = storageManager
})
+
+ // 本地存储路径校验与创建
+ if (selectedProvider === 'local') {
+ const localBase = (devConfigs.local as any).basePath as string
+ try {
+ if (!path.isAbsolute(localBase)) {
+ logger.storage.warn(`LOCAL basePath is not absolute: ${localBase}`)
+ }
+ await import('node:fs').then(async (m) => {
+ const fs = m.promises as typeof import('node:fs').promises
+ await fs.mkdir(localBase, { recursive: true })
+ })
+ logger.storage.success(`Local storage ready at: ${localBase}`)
+ } catch (err) {
+ logger.storage.error('Failed to prepare local storage directory', err)
+ }
+ }
})
diff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].ts
new file mode 100644
index 00000000..200c1f20
--- /dev/null
+++ b/server/routes/storage/[...path].ts
@@ -0,0 +1,108 @@
+import path from 'node:path'
+import { createReadStream, promises as fs } from 'node:fs'
+// lightweight: avoid TS type dep; fallback when not resolvable
+const guessContentType = (filePath: string): string => {
+ const ext = (filePath.split('.').pop() || '').toLowerCase()
+ switch (ext) {
+ case 'jpg':
+ case 'jpeg':
+ return 'image/jpeg'
+ case 'png':
+ return 'image/png'
+ case 'webp':
+ return 'image/webp'
+ case 'gif':
+ return 'image/gif'
+ case 'bmp':
+ return 'image/bmp'
+ case 'tif':
+ case 'tiff':
+ return 'image/tiff'
+ case 'mp4':
+ return 'video/mp4'
+ case 'mov':
+ return 'video/quicktime'
+ case 'json':
+ return 'application/json'
+ default:
+ return 'application/octet-stream'
+ }
+}
+import { getStorageManager } from '../../plugins/storage'
+
+export default defineEventHandler(async (event) => {
+ const config = useRuntimeConfig(event)
+ const manager = getStorageManager()
+ const provider = manager.getProvider()
+
+ if ((provider as any).config?.provider !== 'local') {
+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })
+ }
+
+ const p = getRouterParam(event, 'path') || ''
+ const relPathRaw = Array.isArray(p) ? p.join('/') : p
+ const relPath = relPathRaw.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')
+
+ // 阻止路径穿越
+ if (relPath.includes('..')) {
+ throw createError({ statusCode: 400, statusMessage: 'Invalid path' })
+ }
+
+ const basePath = (provider as any).config.basePath as string
+ const absolute = path.resolve(basePath, relPath)
+
+ // 再次确认目标仍在 basePath 内
+ if (!absolute.startsWith(path.resolve(basePath) + path.sep)) {
+ throw createError({ statusCode: 400, statusMessage: 'Invalid path' })
+ }
+
+ try {
+ const stat = await fs.stat(absolute)
+ if (!stat.isFile()) {
+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })
+ }
+
+ // 设置缓存头
+ const etag = `W/"${stat.size}-${stat.mtimeMs}"`
+ setHeader(event, 'ETag', etag)
+ setHeader(event, 'Last-Modified', stat.mtime.toUTCString())
+ setHeader(event, 'Cache-Control', 'public, max-age=31536000, immutable')
+
+ // Content-Type
+ const contentType = guessContentType(absolute)
+ setHeader(event, 'Content-Type', contentType)
+
+ // 条件请求
+ const inm = getHeader(event, 'if-none-match')
+ const ims = getHeader(event, 'if-modified-since')
+ if (inm === etag || (ims && new Date(ims).getTime() >= stat.mtime.getTime())) {
+ event.node.res.statusCode = 304
+ return null
+ }
+
+ // Range 支持
+ const range = getHeader(event, 'range')
+ if (range) {
+ const matches = /^bytes=(\d*)-(\d*)$/.exec(range)
+ if (matches) {
+ const start = matches[1] ? parseInt(matches[1], 10) : 0
+ const end = matches[2] ? parseInt(matches[2], 10) : stat.size - 1
+ if (start <= end && end < stat.size) {
+ event.node.res.statusCode = 206
+ setHeader(event, 'Content-Range', `bytes ${start}-${end}/${stat.size}`)
+ setHeader(event, 'Accept-Ranges', 'bytes')
+ event.node.res.setHeader('Content-Length', String(end - start + 1))
+ const stream = createReadStream(absolute, { start, end })
+ return sendStream(event, stream)
+ }
+ }
+ }
+ } catch {
+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })
+ }
+
+ const stream = createReadStream(absolute)
+ return sendStream(event, stream)
+})
+
+
diff --git a/server/services/image/processor.ts b/server/services/image/processor.ts
index c994d842..da676ab6 100644
--- a/server/services/image/processor.ts
+++ b/server/services/image/processor.ts
@@ -16,6 +16,33 @@ export interface ImageMeta {
height: number
format: string
}
+// Minimal JPEG size extractor as last-resort fallback
+const tryExtractJpegSize = (buffer: Buffer): { width: number; height: number } | null => {
+ // JPEG starts with 0xFFD8
+ if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null
+ let offset = 2
+ while (offset + 9 < buffer.length) {
+ if (buffer[offset] !== 0xff) { offset++; continue }
+ const marker = buffer[offset + 1]
+ offset += 2
+ // Skip padding FFs
+ if (marker === 0xff) continue
+ // Standalone markers without length
+ if (marker === 0xd8 || marker === 0xd9) continue
+ const length = (buffer[offset] << 8) + buffer[offset + 1]
+ if (length < 2) break
+ // SOF0..SOF3 and SOF5..SOF7 indicate dimensions
+ if ((marker >= 0xc0 && marker <= 0xc3) || (marker >= 0xc5 && marker <= 0xc7)) {
+ if (offset + 7 >= buffer.length) break
+ const height = (buffer[offset + 3] << 8) + buffer[offset + 4]
+ const width = (buffer[offset + 5] << 8) + buffer[offset + 6]
+ if (width > 0 && height > 0) return { width, height }
+ break
+ }
+ offset += length
+ }
+ return null
+}
const isBitmap = (buffer: Buffer) => {
if (buffer.length < 2) return false
@@ -28,13 +55,44 @@ const getMetadataWithSharp = async (
): Promise<ImageMeta | null> => {
try {
return await withRetry(async () => {
- const metadata = await sharpInst.metadata()
+ let metadata = await sharpInst.metadata()
+
+ // Fallback 1: try rotate() which can populate dimensions for some orientations
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ try {
+ metadata = await sharpInst.clone().rotate().metadata()
+ } catch {}
+ }
+
+ // Fallback 2: re-instantiate sharp from a fresh buffer
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ try {
+ const buf = await sharpInst.clone().toBuffer()
+ metadata = await sharp(buf).metadata()
+ } catch {}
+ }
+
+ // Fallback 3: force re-encode to JPEG then read metadata
+ if (!metadata.height || !metadata.width || !metadata.format) {
+ try {
+ const jpegBuf = await sharpInst.clone().jpeg().toBuffer()
+ metadata = await sharp(jpegBuf).metadata()
+ if (!metadata.height || !metadata.width) {
+ const dims = tryExtractJpegSize(jpegBuf)
+ if (dims) {
+ metadata.width = dims.width
+ metadata.height = dims.height
+ metadata.format = metadata.format || 'jpeg'
+ }
+ }
+ } catch {}
+ }
if (!metadata.height || !metadata.width || !metadata.format) {
- logger.image.warn('Incomplete metadata received:', {
- hasHeight: !!metadata.height,
- hasWidth: !!metadata.width,
- hasFormat: !!metadata.format
+ logger.image.warn('Incomplete metadata received:', {
+ hasHeight: !!metadata.height,
+ hasWidth: !!metadata.width,
+ hasFormat: !!metadata.format,
})
return null
}
@@ -219,7 +277,8 @@ export const processImageMetadataAndSharp = async (
s3key: string,
): Promise<ProcessedImageData | null> => {
try {
- let sharpInst = sharp(buffer)
+ // Disable input pixel limit to avoid failures on very large images
+ let sharpInst = sharp(buffer, { limitInputPixels: false })
let convertedBuffer = buffer
if (isBitmap(buffer)) {
@@ -235,6 +294,7 @@ export const processImageMetadataAndSharp = async (
const metadata = await getMetadataWithSharp(sharpInst)
if (!metadata) {
+ logger.image.error('Metadata extraction returned null (after fallbacks):', s3key)
return null
}
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index 16b15116..904ebfbb 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -235,8 +235,18 @@ export class QueueManager {
try {
this.logger.info(`Start processing task ${taskId}: ${storageKey}`)
- const storageObject = await storageProvider.getFileMeta(storageKey)
-
+ let storageObject = await storageProvider.getFileMeta(storageKey)
+ if (!storageObject) {
+ // Fallback: try read the file directly to confirm existence (e.g., local provider)
+ const maybeBuffer = await storageProvider.get(storageKey)
+ if (maybeBuffer) {
+ storageObject = {
+ key: storageKey,
+ size: maybeBuffer.length,
+ lastModified: new Date(),
+ }
+ }
+ }
if (!storageObject) {
throw new Error(`Storage object not found`)
}
@@ -388,8 +398,17 @@ export class QueueManager {
`Start processing LivePhoto detection task ${taskId}: ${videoKey}`,
)
- const storageObject = await storageProvider.getFileMeta(videoKey)
-
+ let storageObject = await storageProvider.getFileMeta(videoKey)
+ if (!storageObject) {
+ const maybeBuffer = await storageProvider.get(videoKey)
+ if (maybeBuffer) {
+ storageObject = {
+ key: videoKey,
+ size: maybeBuffer.length,
+ lastModified: new Date(),
+ }
+ }
+ }
if (!storageObject) {
throw new Error(`Storage object not found`)
}
diff --git a/server/services/storage/index.ts b/server/services/storage/index.ts
index 2e13e301..c7c1d24c 100644
--- a/server/services/storage/index.ts
+++ b/server/services/storage/index.ts
@@ -5,3 +5,4 @@ export { StorageProviderFactory, StorageManager } from './manager'
export { S3StorageProvider } from './providers/s3'
export { HubR2StorageProvider } from './providers/hub-r2'
export { GitHubStorageProvider } from './providers/github'
+export { LocalStorageProvider } from './providers/local'
diff --git a/server/services/storage/interfaces.ts b/server/services/storage/interfaces.ts
index bfb1d962..0796fcfe 100644
--- a/server/services/storage/interfaces.ts
+++ b/server/services/storage/interfaces.ts
@@ -34,10 +34,21 @@ export type GitHubStorageConfig = {
token?: string
}
+export type LocalStorageConfig = {
+ provider: 'local'
+ /** Absolute directory where files are stored */
+ basePath: string
+ /** Public base URL to serve files, e.g. /storage or https://domain.com/storage */
+ baseUrl?: string
+ /** Optional prefix for logical keys within basePath */
+ prefix?: string
+}
+
export type StorageConfig =
| S3StorageConfig
| HubR2StorageConfig
| GitHubStorageConfig
+ | LocalStorageConfig
export interface UploadOptions {
contentType?: string
diff --git a/server/services/storage/manager.ts b/server/services/storage/manager.ts
index 1bfb9ea6..f823392f 100644
--- a/server/services/storage/manager.ts
+++ b/server/services/storage/manager.ts
@@ -2,6 +2,7 @@ import type { StorageConfig, StorageProvider } from '.';
import { S3StorageProvider } from '.'
import type { Logger } from '../../utils/logger'
import { HubR2StorageProvider } from './providers/hub-r2'
+import { LocalStorageProvider } from './providers/local'
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class StorageProviderFactory {
@@ -14,6 +15,8 @@ export class StorageProviderFactory {
return new S3StorageProvider(config, logger)
case 'hub-r2':
return new HubR2StorageProvider(config, logger)
+ case 'local':
+ return new LocalStorageProvider(config, logger)
case 'github':
// TODO: Implement GitHub storage provider
throw new Error('GitHub storage provider not implemented yet')
diff --git a/server/services/storage/providers/local.ts b/server/services/storage/providers/local.ts
new file mode 100644
index 00000000..3ccdb6cc
--- /dev/null
+++ b/server/services/storage/providers/local.ts
@@ -0,0 +1,137 @@
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import type {
+ LocalStorageConfig,
+ StorageObject,
+ StorageProvider,
+} from '../interfaces'
+
+const ensureDir = async (dirPath: string) => {
+ await fs.mkdir(dirPath, { recursive: true })
+}
+
+const sanitizeKey = (key: string) => key.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')
+
+const combinePrefixAndKey = (prefix: string | undefined, key: string) => {
+ const cleanPrefix = (prefix || '').replace(/\/+$/, '')
+ const cleanKey = key.replace(/^\/+/, '')
+ if (!cleanPrefix) return cleanKey
+ return cleanKey.startsWith(cleanPrefix + '/')
+ ? cleanKey
+ : `${cleanPrefix}/${cleanKey}`
+}
+
+export class LocalStorageProvider implements StorageProvider {
+ config: LocalStorageConfig
+ private logger?: Logger['storage']
+
+ constructor(config: LocalStorageConfig, logger?: Logger['storage']) {
+ this.config = config
+ this.logger = logger
+ }
+
+ private resolveAbsoluteKey(key: string): { absFile: string; relKey: string } {
+ const relKey = sanitizeKey(combinePrefixAndKey(this.config.prefix, key))
+ const absFile = path.resolve(this.config.basePath, relKey)
+ return { absFile, relKey }
+ }
+
+ async create(key: string, fileBuffer: Buffer): Promise<StorageObject> {
+ const { absFile, relKey } = this.resolveAbsoluteKey(key)
+ await ensureDir(path.dirname(absFile))
+ // 原子写入:写到临时文件再重命名
+ const tempFile = `${absFile}.tmp-${Date.now()}`
+ await fs.writeFile(tempFile, fileBuffer)
+ await fs.rename(tempFile, absFile)
+ const stat = await fs.stat(absFile)
+ this.logger?.success?.(`Saved file: ${absFile}`)
+ return {
+ key: relKey,
+ size: stat.size,
+ lastModified: stat.mtime,
+ }
+ }
+
+ async delete(key: string): Promise<void> {
+ const { absFile } = this.resolveAbsoluteKey(key)
+ try {
+ await fs.unlink(absFile)
+ this.logger?.success?.(`Deleted file: ${absFile}`)
+ } catch (err) {
+ // ignore if not exists
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
+ }
+ }
+
+ async get(key: string): Promise<Buffer | null> {
+ const { absFile } = this.resolveAbsoluteKey(key)
+ try {
+ return await fs.readFile(absFile)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw err
+ }
+ }
+
+ getPublicUrl(key: string): string {
+ const relKey = sanitizeKey(combinePrefixAndKey(this.config.prefix, key))
+ const base = (this.config.baseUrl || '/storage').replace(/\/+$/, '')
+ return `${base}/${relKey}`
+ }
+
+ async listAll(): Promise<StorageObject[]> {
+ const results: StorageObject[] = []
+ const baseDir = this.config.prefix
+ ? path.resolve(this.config.basePath, this.config.prefix)
+ : this.config.basePath
+
+ const walk = async (dir: string, relBase: string) => {
+ const entries = await fs.readdir(dir, { withFileTypes: true })
+ for (const entry of entries) {
+ const abs = path.join(dir, entry.name)
+ const rel = sanitizeKey(path.join(relBase, entry.name))
+ if (entry.isDirectory()) {
+ await walk(abs, rel)
+ } else if (entry.isFile()) {
+ const stat = await fs.stat(abs)
+ results.push({ key: rel, size: stat.size, lastModified: stat.mtime })
+ }
+ }
+ }
+
+ await ensureDir(baseDir)
+ await walk(baseDir, this.config.prefix || '')
+ return results
+ }
+
+ async listImages(): Promise<StorageObject[]> {
+ const all = await this.listAll()
+ return all.filter((o) => /\.(png|jpe?g|webp|gif|bmp|tiff?)$/i.test(o.key))
+ }
+
+ async getFileMeta(key: string): Promise<StorageObject | null> {
+ // First try with combined prefix
+ const { absFile, relKey } = this.resolveAbsoluteKey(key)
+ try {
+ const stat = await fs.stat(absFile)
+ if (!stat.isFile()) return null
+ return { key: relKey, size: stat.size, lastModified: stat.mtime }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
+ }
+
+ // Fallback: try without adding prefix (in case key already contains it or was stored raw)
+ const rawRel = sanitizeKey(key)
+ const rawAbs = path.resolve(this.config.basePath, rawRel)
+ try {
+ const stat = await fs.stat(rawAbs)
+ if (!stat.isFile()) return null
+ return { key: rawRel, size: stat.size, lastModified: stat.mtime }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw err
+ }
+ }
+}
+
+
diff --git a/server/utils/upload-messages.ts b/server/utils/upload-messages.ts
new file mode 100644
index 00000000..d5e23ee6
--- /dev/null
+++ b/server/utils/upload-messages.ts
@@ -0,0 +1,191 @@
+/**
+ * 上传相关的提示消息
+ */
+
+export const UploadMessages = {
+ // 重复文件相关
+ duplicate: {
+ block: {
+ zh: (fileName: string) => ({
+ title: '文件已存在',
+ message: `照片 "${fileName}" 已存在,无法上传重复文件`,
+ suggestion: '您可以:1) 重命名文件后重新上传;2) 在设置中切换到"警告模式"以允许覆盖',
+ }),
+ en: (fileName: string) => ({
+ title: 'File Already Exists',
+ message: `Photo "${fileName}" already exists and duplicate uploads are not allowed`,
+ suggestion: 'You can: 1) Rename the file and upload again; 2) Switch to "warn mode" in settings to allow overwriting',
+ }),
+ },
+ skip: {
+ zh: (fileName: string, photoInfo?: any) => ({
+ title: '跳过重复文件',
+ message: `照片 "${fileName}" 已存在,已自动跳过上传`,
+ info: photoInfo ? `现有照片拍摄于 ${photoInfo.dateTaken || '未知日期'}` : undefined,
+ }),
+ en: (fileName: string, photoInfo?: any) => ({
+ title: 'Duplicate File Skipped',
+ message: `Photo "${fileName}" already exists and has been automatically skipped`,
+ info: photoInfo ? `Existing photo taken on ${photoInfo.dateTaken || 'unknown date'}` : undefined,
+ }),
+ },
+ warn: {
+ zh: (fileName: string, photoInfo?: any) => ({
+ title: '检测到重复文件',
+ message: `照片 "${fileName}" 已存在,继续上传将会覆盖现有照片`,
+ warning: '覆盖后,原有照片的所有信息(EXIF、标签、表态等)将被替换',
+ info: photoInfo ? `现有照片:${photoInfo.title || fileName},拍摄于 ${photoInfo.dateTaken || '未知日期'}` : undefined,
+ }),
+ en: (fileName: string, photoInfo?: any) => ({
+ title: 'Duplicate File Detected',
+ message: `Photo "${fileName}" already exists. Continuing will overwrite the existing photo`,
+ warning: 'After overwriting, all information of the original photo (EXIF, tags, reactions, etc.) will be replaced',
+ info: photoInfo ? `Existing photo: ${photoInfo.title || fileName}, taken on ${photoInfo.dateTaken || 'unknown date'}` : undefined,
+ }),
+ },
+ },
+
+ // 成功消息
+ success: {
+ upload: {
+ zh: (count: number) => ({
+ title: '上传成功',
+ message: count === 1
+ ? '照片已成功上传,正在处理中...'
+ : `已成功上传 ${count} 张照片,正在处理中...`,
+ }),
+ en: (count: number) => ({
+ title: 'Upload Successful',
+ message: count === 1
+ ? 'Photo uploaded successfully, processing...'
+ : `${count} photos uploaded successfully, processing...`,
+ }),
+ },
+ check: {
+ zh: (total: number, duplicates: number) => ({
+ title: '检查完成',
+ message: `已检查 ${total} 个文件,发现 ${duplicates} 个重复文件`,
+ }),
+ en: (total: number, duplicates: number) => ({
+ title: 'Check Complete',
+ message: `Checked ${total} files, found ${duplicates} duplicates`,
+ }),
+ },
+ },
+
+ // 错误消息
+ error: {
+ required: {
+ zh: (field: string) => ({
+ title: '缺少必填参数',
+ message: `请提供 ${field} 参数`,
+ }),
+ en: (field: string) => ({
+ title: 'Missing Required Parameter',
+ message: `Please provide ${field} parameter`,
+ }),
+ },
+ invalidType: {
+ zh: (type: string, allowed: string[]) => ({
+ title: '不支持的文件类型',
+ message: `不支持的媒体类型:${type}`,
+ suggestion: `允许的类型:${allowed.join(', ')}`,
+ }),
+ en: (type: string, allowed: string[]) => ({
+ title: 'Unsupported File Type',
+ message: `Unsupported media type: ${type}`,
+ suggestion: `Allowed types: ${allowed.join(', ')}`,
+ }),
+ },
+ tooLarge: {
+ zh: (size: number, maxSize: number) => ({
+ title: '文件太大',
+ message: `文件大小 ${(size / 1024 / 1024).toFixed(2)}MB 超过限制`,
+ suggestion: `最大允许 ${maxSize}MB`,
+ }),
+ en: (size: number, maxSize: number) => ({
+ title: 'File Too Large',
+ message: `File size ${(size / 1024 / 1024).toFixed(2)}MB exceeds limit`,
+ suggestion: `Maximum allowed: ${maxSize}MB`,
+ }),
+ },
+ uploadFailed: {
+ zh: (reason?: string) => ({
+ title: '上传失败',
+ message: reason || '上传过程中发生错误,请稍后重试',
+ }),
+ en: (reason?: string) => ({
+ title: 'Upload Failed',
+ message: reason || 'An error occurred during upload, please try again later',
+ }),
+ },
+ },
+}
+
+/**
+ * 获取消息内容(支持语言参数)
+ */
+export function getMessage(
+ category: keyof typeof UploadMessages,
+ type: string,
+ lang: 'zh' | 'en' = 'zh',
+ ...args: any[]
+) {
+ try {
+ const messageGroup = UploadMessages[category] as any
+ if (!messageGroup || !messageGroup[type]) {
+ return null
+ }
+
+ const messageFunc = messageGroup[type][lang]
+ if (typeof messageFunc === 'function') {
+ return messageFunc(...args)
+ }
+
+ return messageFunc
+ } catch (error) {
+ return null
+ }
+}
+
+/**
+ * 从请求头获取客户端语言偏好
+ */
+export function getPreferredLanguage(event: any): 'zh' | 'en' {
+ const acceptLanguage = getHeader(event, 'accept-language') || ''
+
+ // 检查是否包含中文
+ if (acceptLanguage.includes('zh')) {
+ return 'zh'
+ }
+
+ return 'en'
+}
+
+/**
+ * 创建格式化的错误响应
+ */
+export function createFormattedError(
+ statusCode: number,
+ messageKey: string,
+ event: any,
+ ...args: any[]
+) {
+ const lang = getPreferredLanguage(event)
+ const [category, type] = messageKey.split('.')
+ const message = getMessage(category as any, type, lang, ...args)
+
+ if (message) {
+ return createError({
+ statusCode,
+ statusMessage: message.title,
+ data: message,
+ })
+ }
+
+ return createError({
+ statusCode,
+ statusMessage: 'An error occurred',
+ })
+}
+