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: 添加预签名 URL 生成及前端直接 PUT 文件到 S3,添加进度上传组件,优化日期时间和文件大小展示

Timothy Yin3783fca84dc1
diff --git a/app/components/masonry/PhotoItem.client.vue b/app/components/masonry/PhotoItem.client.vue
index 47d61e2d..8d62dcca 100644
--- a/app/components/masonry/PhotoItem.client.vue
+++ b/app/components/masonry/PhotoItem.client.vue
@@ -31,7 +31,7 @@ const intersectionObserverRef = ref<IntersectionObserver | null>(null)
const containerHeight = computed(() => {
// Get the actual container width to calculate proper aspect ratio
const currentWidth = containerWidth.value || 280
-
+
// Use actual dimensions from photo data if available
if (props.photo.width && props.photo.height) {
const aspectRatio = props.photo.height / props.photo.width
@@ -78,16 +78,6 @@ const checkImageLoaded = (img: HTMLImageElement) => {
}
}
-const formatDate = (date: string | Date): string => {
- if (!date) return ''
- const d = new Date(date)
- return d.toLocaleDateString('en-US', {
- year: 'numeric',
- month: 'short',
- day: 'numeric',
- })
-}
-
const formatExposureTime = (
exposureTime: string | number | undefined,
): string => {
@@ -139,7 +129,7 @@ onMounted(() => {
nextTick(() => {
if (photoRef.value) {
containerWidth.value = photoRef.value.offsetWidth
-
+
// Set up resize observer to track width changes
const resizeObserver = new ResizeObserver(() => {
if (photoRef.value) {
@@ -229,9 +219,7 @@ onUnmounted(() => {
}"
@click="emit('openViewer', props.index)"
>
- <div
- class="relative group overflow-hidden transition-all duration-300"
- >
+ <div class="relative group overflow-hidden transition-all duration-300">
<!-- Thumbhash 组件占位符 -->
<div
v-if="isLoading && photo.thumbnailHash"
@@ -289,9 +277,9 @@ onUnmounted(() => {
</p>
<p
v-if="photo.dateTaken"
- class="text-xs opacity-80"
+ class="text-xs font-medium opacity-80"
>
- {{ formatDate(photo.dateTaken) }}
+ {{ $dayjs(photo.dateTaken).format('YYYY-MM-DD') }}
</p>
</div>
<div
diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vue
index 77d10c81..3014cebe 100644
--- a/app/components/photo/InfoPanel.vue
+++ b/app/components/photo/InfoPanel.vue
@@ -10,6 +10,8 @@ interface Props {
onClose?: () => void
}
+const dayjs = useDayjs()
+
const props = defineProps<Props>()
// 格式化曝光时间
@@ -52,26 +54,6 @@ const formatExposureTime = (
}
}
-// 格式化日期
-const formatDate = (date: string | undefined): string => {
- if (!date) return ''
- const d = new Date(date)
- return d.toLocaleDateString('zh-CN', {
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- hour: '2-digit',
- minute: '2-digit',
- })
-}
-
-// 格式化文件大小
-const formatFileSize = (bytes: number | undefined): string => {
- if (!bytes) return ''
- const mb = bytes / 1024 / 1024
- return `${mb.toFixed(2)} MB`
-}
-
const gpsCoordinates = computed(() => {
if (!props.exifData) return null
const { GPSLatitude, GPSLongitude } = props.exifData
@@ -102,7 +84,7 @@ const formatedExifData = computed<Record<string, KVData[]>>(() => {
props.currentPhoto.fileSize
? {
label: '文件大小',
- value: formatFileSize(props.currentPhoto.fileSize),
+ value: formatBytes(props.currentPhoto.fileSize),
icon: 'tabler:database',
}
: null,
@@ -144,7 +126,7 @@ const formatedExifData = computed<Record<string, KVData[]>>(() => {
props.exifData?.DateTimeOriginal
? {
label: '拍摄时间',
- value: formatDate(props.exifData.DateTimeOriginal),
+ value: dayjs(props.exifData.DateTimeOriginal).format('YYYY-MM-DD HH:mm:ss'),
icon: 'tabler:calendar',
}
: null,
@@ -383,7 +365,7 @@ const isMobile = useMediaQuery('(max-width: 768px)')
:transition="{ type: 'spring', duration: 0.4, bounce: 0, delay: 0.1 }"
class="bg-black/30 backdrop-blur-xl border-white/10"
:class="{
- 'fixed inset-x-2 bottom-2 max-h-[80vh] border rounded-xl z-50 flex flex-col': isMobile,
+ 'fixed inset-x-2 bottom-2 max-h-[70vh] border rounded-xl z-50 flex flex-col': isMobile,
'w-80 border-l': !isMobile,
}"
>
diff --git a/app/composables/useUpload.ts b/app/composables/useUpload.ts
new file mode 100644
index 00000000..ed04f939
--- /dev/null
+++ b/app/composables/useUpload.ts
@@ -0,0 +1,324 @@
+export interface UploadProgress {
+ loaded: number
+ total: number
+ percentage: number
+ speed?: number // bytes per second
+ timeRemaining?: number // seconds
+}
+
+export interface UploadStatus {
+ status: 'idle' | 'uploading' | 'success' | 'error' | 'aborted'
+ progress: UploadProgress
+ error?: string
+ startTime?: number
+ endTime?: number
+}
+
+export interface UploadCallbacks {
+ onProgress?: (progress: UploadProgress) => void
+ onStatusChange?: (status: UploadStatus['status']) => void
+ onSuccess?: (response: XMLHttpRequest) => void
+ onError?: (error: string, xhr: XMLHttpRequest) => void
+ onAbort?: () => void
+}
+
+export interface UseUploadOptions {
+ timeout?: number // 超时时间(毫秒)
+ withCredentials?: boolean
+ headers?: Record<string, string>
+ speedSampleSize?: number // 用于计算速度的样本数量
+}
+
+export function useUpload(options: UseUploadOptions = {}) {
+ const {
+ timeout = 0,
+ withCredentials = false,
+ headers = {},
+ speedSampleSize = 5
+ } = options
+
+ // 响应式状态
+ const uploadStatus = ref<UploadStatus>({
+ status: 'idle',
+ progress: {
+ loaded: 0,
+ total: 0,
+ percentage: 0,
+ }
+ })
+
+ // 当前的 XMLHttpRequest 实例
+ let currentXHR: XMLHttpRequest | null = null
+
+ // 用于计算速度的数据点
+ const speedSamples: Array<{ timestamp: number; loaded: number }> = []
+
+ // 计算上传速度和剩余时间
+ const calculateSpeed = (loaded: number): { speed: number; timeRemaining?: number } => {
+ const now = Date.now()
+ speedSamples.push({ timestamp: now, loaded })
+
+ // 保持样本数量在限制内
+ if (speedSamples.length > speedSampleSize) {
+ speedSamples.shift()
+ }
+
+ if (speedSamples.length < 2) {
+ return { speed: 0 }
+ }
+
+ // 计算平均速度
+ const firstSample = speedSamples[0]
+ const lastSample = speedSamples[speedSamples.length - 1]
+
+ if (!firstSample || !lastSample) {
+ return { speed: 0 }
+ }
+
+ const timeDiff = (lastSample.timestamp - firstSample.timestamp) / 1000 // 转换为秒
+ const bytesDiff = lastSample.loaded - firstSample.loaded
+
+ const speed = timeDiff > 0 ? bytesDiff / timeDiff : 0
+
+ // 计算剩余时间
+ const total = uploadStatus.value.progress.total
+ const remaining = total - loaded
+ const timeRemaining = speed > 0 ? remaining / speed : undefined
+
+ return { speed, timeRemaining }
+ }
+
+ // 更新状态
+ const updateStatus = (updates: Partial<UploadStatus>) => {
+ uploadStatus.value = { ...uploadStatus.value, ...updates }
+ }
+
+ // 更新进度
+ const updateProgress = (loaded: number, total: number) => {
+ const percentage = total > 0 ? Math.round((loaded / total) * 100) : 0
+ const { speed, timeRemaining } = calculateSpeed(loaded)
+
+ const progress: UploadProgress = {
+ loaded,
+ total,
+ percentage,
+ speed,
+ timeRemaining
+ }
+
+ updateStatus({ progress })
+ }
+
+ // 重置状态
+ const resetStatus = () => {
+ speedSamples.length = 0
+ updateStatus({
+ status: 'idle',
+ progress: {
+ loaded: 0,
+ total: 0,
+ percentage: 0,
+ },
+ error: undefined,
+ startTime: undefined,
+ endTime: undefined
+ })
+ }
+
+ // 主要的上传函数
+ const uploadFile = async (
+ file: File,
+ signedUrl: string,
+ callbacks: UploadCallbacks = {}
+ ): Promise<XMLHttpRequest> => {
+ // 重置状态
+ resetStatus()
+
+ return new Promise((resolve, reject) => {
+ // 创建新的 XHR 实例
+ currentXHR = new XMLHttpRequest()
+ const xhr = currentXHR
+
+ // 设置超时
+ if (timeout > 0) {
+ xhr.timeout = timeout
+ }
+
+ // 设置是否携带凭证
+ xhr.withCredentials = withCredentials
+
+ // 记录开始时间
+ const startTime = Date.now()
+ updateStatus({ status: 'uploading', startTime })
+ callbacks.onStatusChange?.('uploading')
+
+ // 进度事件处理
+ xhr.upload.addEventListener('progress', (event) => {
+ if (event.lengthComputable) {
+ updateProgress(event.loaded, event.total)
+ callbacks.onProgress?.(uploadStatus.value.progress)
+ }
+ })
+
+ // 成功处理
+ xhr.addEventListener('load', () => {
+ const endTime = Date.now()
+ updateStatus({ status: 'success', endTime })
+ callbacks.onStatusChange?.('success')
+ callbacks.onSuccess?.(xhr)
+ resolve(xhr)
+ })
+
+ // 错误处理
+ 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))
+ })
+
+ // 超时处理
+ 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))
+ })
+
+ // 中止处理
+ xhr.addEventListener('abort', () => {
+ const endTime = Date.now()
+ updateStatus({ status: 'aborted', endTime })
+ callbacks.onStatusChange?.('aborted')
+ callbacks.onAbort?.()
+ reject(new Error('上传已中止'))
+ })
+
+ // 状态变化处理
+ xhr.addEventListener('readystatechange', () => {
+ if (xhr.readyState === XMLHttpRequest.DONE) {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ // 成功情况在 load 事件中处理
+ return
+ } else if (xhr.status >= 400) {
+ const endTime = Date.now()
+ let error = `HTTP 错误: ${xhr.status}`
+
+ // 尝试获取更详细的错误信息
+ try {
+ const responseText = xhr.responseText
+ if (responseText) {
+ error += ` - ${responseText}`
+ }
+ } catch (e) {
+ // 忽略解析错误
+ }
+
+ updateStatus({ status: 'error', error, endTime })
+ callbacks.onStatusChange?.('error')
+ callbacks.onError?.(error, xhr)
+ }
+ }
+ })
+
+ // 准备请求
+ xhr.open('PUT', signedUrl)
+
+ // 设置请求头
+ xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream')
+
+ // 设置自定义请求头
+ Object.entries(headers).forEach(([key, value]) => {
+ xhr.setRequestHeader(key, value)
+ })
+
+ // 开始上传
+ xhr.send(file)
+ })
+ }
+
+ // 中止上传
+ const abortUpload = () => {
+ if (currentXHR && uploadStatus.value.status === 'uploading') {
+ currentXHR.abort()
+ }
+ }
+
+ // 格式化字节大小
+ const formatBytes = (bytes: number): string => {
+ if (bytes === 0) return '0 B'
+ const k = 1024
+ const sizes = ['B', 'KB', 'MB', 'GB']
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
+ }
+
+ // 格式化时间
+ const formatTime = (seconds: number): string => {
+ if (!isFinite(seconds) || seconds < 0) return '计算中...'
+
+ const hours = Math.floor(seconds / 3600)
+ const minutes = Math.floor((seconds % 3600) / 60)
+ const secs = Math.floor(seconds % 60)
+
+ if (hours > 0) {
+ return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
+ } else if (minutes > 0) {
+ return `${minutes}:${secs.toString().padStart(2, '0')}`
+ } else {
+ return `${secs}秒`
+ }
+ }
+
+ // 计算属性
+ const isUploading = computed(() => uploadStatus.value.status === 'uploading')
+ const isIdle = computed(() => uploadStatus.value.status === 'idle')
+ const isSuccess = computed(() => uploadStatus.value.status === 'success')
+ const isError = computed(() => uploadStatus.value.status === 'error')
+ const isAborted = computed(() => uploadStatus.value.status === 'aborted')
+ const canAbort = computed(() => isUploading.value && currentXHR !== null)
+
+ // 格式化的进度信息
+ const formattedProgress = computed(() => {
+ const { loaded, total, percentage, speed, timeRemaining } = uploadStatus.value.progress
+ return {
+ percentage,
+ loadedText: formatBytes(loaded),
+ totalText: formatBytes(total),
+ speedText: speed ? `${formatBytes(speed)}/s` : '',
+ timeRemainingText: timeRemaining ? formatTime(timeRemaining) : '',
+ progressText: `${formatBytes(loaded)} / ${formatBytes(total)} (${percentage}%)`
+ }
+ })
+
+ // 清理函数
+ onUnmounted(() => {
+ abortUpload()
+ currentXHR = null
+ })
+
+ return {
+ // 状态
+ uploadStatus: readonly(uploadStatus),
+
+ // 计算属性
+ isUploading,
+ isIdle,
+ isSuccess,
+ isError,
+ isAborted,
+ canAbort,
+ formattedProgress,
+
+ // 方法
+ uploadFile,
+ abortUpload,
+ resetStatus,
+ formatBytes,
+ formatTime
+ }
+}
diff --git a/app/pages/dashboard/index.vue b/app/pages/dashboard/index.vue
index eddbe2ba..2cbdb37c 100644
--- a/app/pages/dashboard/index.vue
+++ b/app/pages/dashboard/index.vue
@@ -189,17 +189,20 @@ onBeforeUnmount(() => {
<img
:src="photo.thumbnailUrl || ''"
alt="Photo thumbnail"
- class="w-full h-full rounded"
+ class="w-full h-full rounded object-cover"
/>
</div>
<div class="flex-1 min-w-0">
<p class="font-medium truncate">{{ photo.title || photo.id }}</p>
- <p class="text-sm text-neutral-500">
- {{
- photo.dateTaken
- ? new Date(photo.dateTaken).toLocaleDateString('zh-CN')
- : '未知日期'
- }}
+ <p class="text-sm text-neutral-500 inline-flex gap-2">
+ <span>
+ {{
+ photo.dateTaken
+ ? $dayjs(photo.dateTaken).format('YYYY-MM-DD')
+ : '未知日期'
+ }}
+ </span>
+ <span>{{ formatBytes(photo.fileSize || 0) }}</span>
</p>
</div>
</div>
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index 02cf5ba5..25af51a2 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -1,39 +1,173 @@
<script lang="ts" setup>
import type { TableColumn } from '@nuxt/ui'
-import type { StorageObject } from '~~/server/services/storage'
import type { Photo } from '~~/server/utils/db'
definePageMeta({
layout: 'dashboard',
})
+const dayjs = useDayjs()
+
const { data, status, refresh } = useFetch('/api/photos')
-// 原生文件上传函数
+// 当前上传的文件信息
+interface UploadingFile {
+ file: File
+ fileName: string
+ status: 'preparing' | 'uploading' | 'processing' | 'completed' | 'error'
+ progress?: number
+ error?: string
+ signedUrlResponse?: { signedUrl: string; fileKey: string; expiresIn: number }
+ // 添加详细进度信息
+ uploadProgress?: {
+ loaded: number
+ total: number
+ percentage: number
+ speed?: number
+ timeRemaining?: number
+ speedText?: string
+ timeRemainingText?: string
+ }
+ // 添加上传管理器的关键方法
+ canAbort?: boolean
+ abortUpload?: () => void
+}
+
+const uploadingFiles = ref<Map<string, UploadingFile>>(new Map())
+
+// 使用预签名 URL 上传文件函数
const uploadImage = async (file: File) => {
- const formData = new FormData()
- formData.append('file', file)
+ const fileName = file.name
+ const fileId = `${Date.now()}-${fileName}`
+
+ // 为每个文件创建独立的上传管理器
+ const uploadManager = useUpload({
+ timeout: 10 * 60 * 1000, // 10分钟超时
+ })
+
+ // 添加到上传队列
+ const uploadingFile: UploadingFile = {
+ file,
+ fileName,
+ status: 'preparing',
+ canAbort: false,
+ abortUpload: () => uploadManager.abortUpload(),
+ }
+ uploadingFiles.value.set(fileId, uploadingFile)
try {
- const response = await $fetch('/api/photos', {
- method: 'PUT',
- body: formData,
- })
+ // 第一步:获取预签名 URL
+ uploadingFile.status = 'preparing'
+ const signedUrlResponse = (await $fetch('/api/photos', {
+ method: 'POST',
+ body: {
+ fileName: file.name,
+ contentType: file.type,
+ },
+ })) as { signedUrl: string; fileKey: string; expiresIn: number }
+
+ uploadingFile.signedUrlResponse = signedUrlResponse
+ uploadingFile.status = 'uploading'
+ uploadingFile.canAbort = true
+
+ // 第二步:使用 composable 上传文件到 S3
+ await uploadManager.uploadFile(file, signedUrlResponse.signedUrl, {
+ onProgress: (progress: UploadProgress) => {
+ // 更新文件特定的进度信息
+ console.log(`文件 ${fileName} 上传进度:`, progress.percentage + '%')
+ uploadingFile.progress = progress.percentage
+ uploadingFile.uploadProgress = {
+ loaded: progress.loaded,
+ total: progress.total,
+ percentage: progress.percentage,
+ speed: progress.speed,
+ timeRemaining: progress.timeRemaining,
+ speedText: progress.speed ? `${formatBytes(progress.speed)}/s` : '',
+ timeRemainingText: progress.timeRemaining
+ ? dayjs.duration(progress.timeRemaining, 'seconds').humanize()
+ : '',
+ }
+
+ // 触发响应式更新
+ uploadingFiles.value = new Map(uploadingFiles.value)
+ },
+ onStatusChange: (status: string) => {
+ console.log(`文件 ${fileName} 上传状态变更:`, status)
+ // 根据状态更新 canAbort
+ uploadingFile.canAbort = status === 'uploading'
+ uploadingFiles.value = new Map(uploadingFiles.value)
+ },
+ onSuccess: async (xhr: XMLHttpRequest) => {
+ console.log(`文件 ${fileName} 上传成功`, xhr.status)
+
+ // 第三步:通知服务器开始处理照片
+ uploadingFile.status = 'processing'
+ uploadingFile.canAbort = false
+ uploadingFiles.value = new Map(uploadingFiles.value)
+
+ try {
+ await $fetch('/api/photos/process', {
+ method: 'POST' as any,
+ body: {
+ fileKey: signedUrlResponse.fileKey,
+ fileName: file.name,
+ fileSize: file.size,
+ },
+ })
+
+ uploadingFile.status = 'completed'
+ uploadingFile.canAbort = false
+ uploadingFiles.value = new Map(uploadingFiles.value)
- return response
+ // 开始状态检查
+ if (!statusInterval) {
+ statusInterval = setInterval(checkProcessingStatus, 2000)
+ }
+ } catch (processError: any) {
+ uploadingFile.status = 'error'
+ uploadingFile.error = `处理失败: ${processError.message}`
+ uploadingFile.canAbort = false
+ uploadingFiles.value = new Map(uploadingFiles.value)
+ throw processError
+ }
+ },
+ onError: (error: string) => {
+ uploadingFile.status = 'error'
+ uploadingFile.error = error
+ uploadingFile.canAbort = false
+ uploadingFiles.value = new Map(uploadingFiles.value)
+ console.error(`文件 ${fileName} 上传失败:`, error)
+ },
+ })
} catch (error: any) {
+ uploadingFile.status = 'error'
+ uploadingFile.error = error.message || '上传失败'
+ uploadingFile.canAbort = false
+ uploadingFiles.value = new Map(uploadingFiles.value)
+
console.error('上传请求失败:', error)
// 提供更详细的错误信息
if (error.response?.status === 401) {
throw new Error('未授权,请重新登录')
- } else if (error.response?.status === 413) {
- throw new Error('文件太大,请选择更小的文件')
- } else if (error.response?.status === 415) {
- throw new Error('不支持的文件格式')
+ } else if (error.message?.includes('CORS')) {
+ throw new Error('跨域请求失败,请检查存储服务的 CORS 配置')
+ } else if (
+ error.message?.includes('NetworkError') ||
+ error.name === 'TypeError'
+ ) {
+ throw new Error('网络连接失败或 CORS 错误,请检查网络连接和存储配置')
+ } else if (error.message?.includes('上传到存储失败')) {
+ throw new Error('文件上传到云存储失败,请重试')
} else {
throw new Error(error.message || '上传失败,请重试')
}
+ } finally {
+ // 上传完成后从队列中移除(延迟移除以便用户看到结果)
+ setTimeout(() => {
+ uploadingFiles.value.delete(fileId)
+ uploadingFiles.value = new Map(uploadingFiles.value)
+ }, 5000)
}
}
@@ -61,6 +195,7 @@ const columns: TableColumn<Photo>[] = [
{
accessorKey: 'fileSize',
header: '文件大小',
+ cell: (info) => formatBytes(info.getValue() as number),
},
{
accessorKey: 'actions',
@@ -154,14 +289,20 @@ const handleUpload = async () => {
processingFiles.value.add(fileName)
toast.add({
- title: '开始处理照片',
- description: `正在后台处理 ${fileName},请稍候...`,
+ title: '开始上传照片',
+ description: `正在上传 ${fileName} 到云存储...`,
color: 'info',
})
try {
await uploadImage(file)
+ toast.add({
+ title: '照片上传成功',
+ description: `${fileName} 已上传,正在后台处理...`,
+ color: 'success',
+ })
+
// 开始状态检查
if (!statusInterval) {
statusInterval = setInterval(checkProcessingStatus, 2000)
@@ -198,20 +339,109 @@ onUnmounted(() => {
<template>
<div class="flex flex-col gap-4 h-full p-4">
- <UAlert
- v-if="processingFiles.size > 0"
- title="照片正在处理"
- :description="`正在后台处理 ${processingFiles.size} 个文件...`"
- icon="svg-spinners:270-ring"
- variant="soft"
- color="info"
- />
+ <!-- 上传进度显示 -->
+ <div
+ v-if="uploadingFiles.size > 0"
+ class="space-y-3"
+ >
+ <h3 class="text-lg font-semibold">上传进度</h3>
+ <div class="space-y-2">
+ <div
+ v-for="[fileId, uploadingFile] of uploadingFiles"
+ :key="fileId"
+ class="p-4 border border-neutral-200 dark:border-neutral-700 rounded-lg"
+ >
+ <div class="flex items-center justify-between mb-2">
+ <span class="font-medium">{{ uploadingFile.fileName }}</span>
+ <div class="flex items-center gap-2">
+ <!-- 状态指示器 -->
+ <UBadge
+ :color="
+ uploadingFile.status === 'completed'
+ ? 'success'
+ : uploadingFile.status === 'error'
+ ? 'error'
+ : uploadingFile.status === 'processing'
+ ? 'info'
+ : 'warning'
+ "
+ variant="soft"
+ >
+ {{
+ uploadingFile.status === 'preparing'
+ ? '准备中'
+ : uploadingFile.status === 'uploading'
+ ? '上传中'
+ : uploadingFile.status === 'processing'
+ ? '处理中'
+ : uploadingFile.status === 'completed'
+ ? '完成'
+ : '错误'
+ }}
+ </UBadge>
+ <!-- 中止按钮 -->
+ <UButton
+ v-if="
+ uploadingFile.status === 'uploading' && uploadingFile.canAbort
+ "
+ size="xs"
+ color="error"
+ variant="soft"
+ icon="tabler:file-x"
+ @click="uploadingFile.abortUpload?.()"
+ >
+ 中止上传
+ </UButton>
+ </div>
+ </div>
+
+ <!-- 进度条 -->
+ <div
+ v-if="
+ uploadingFile.status === 'uploading' &&
+ uploadingFile.progress !== undefined
+ "
+ class="mb-2"
+ >
+ <div
+ class="flex justify-between text-sm text-neutral-600 dark:text-neutral-400 mb-1"
+ >
+ <span>{{ uploadingFile.progress }}%</span>
+ <span v-if="uploadingFile.uploadProgress?.speedText">
+ {{ uploadingFile.uploadProgress.speedText }}
+ </span>
+ </div>
+ <UProgress
+ :model-value="uploadingFile.progress"
+ class="h-2"
+ />
+ <div
+ v-if="uploadingFile.uploadProgress?.timeRemainingText"
+ class="text-xs text-neutral-500 mt-1"
+ >
+ ETA: {{ uploadingFile.uploadProgress.timeRemainingText }}
+ </div>
+ </div>
+
+ <!-- 错误信息 -->
+ <UAlert
+ v-if="uploadingFile.status === 'error' && uploadingFile.error"
+ :description="uploadingFile.error"
+ color="error"
+ variant="soft"
+ class="mt-2"
+ />
+ </div>
+ </div>
+ </div>
+
+ <!-- 文件上传组件 -->
<div class="relative">
<UFileUpload
v-model="selectedFiles"
label="选择照片"
- description="支持 JPEG、PNG、HEIC 格式,最大 128MB"
+ description="支持 JPEG、PNG、HEIC 格式,最大 256MB"
layout="list"
size="xl"
accept="image/jpeg,image/png,image/heic,image/heif"
@@ -225,9 +455,11 @@ onUnmounted(() => {
:disabled="selectedFiles.length === 0"
@click="handleUpload"
>
- 开始上传
+ 上传照片
</UButton>
</div>
+
+ <!-- 照片列表 -->
<div
class="border border-neutral-300 dark:border-neutral-800 rounded overflow-hidden"
>
diff --git a/app/utils/index.ts b/app/utils/index.ts
new file mode 100644
index 00000000..a8b6f15e
--- /dev/null
+++ b/app/utils/index.ts
@@ -0,0 +1,8 @@
+// 格式化字节大小的辅助函数
+export const formatBytes = (bytes: number): string => {
+ if (bytes === 0) return '0 B'
+ const k = 1024
+ const sizes = ['B', 'KB', 'MB', 'GB']
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
+}
diff --git a/nuxt.config.ts b/nuxt.config.ts
index f2af1f98..d8fbbc53 100644
--- a/nuxt.config.ts
+++ b/nuxt.config.ts
@@ -16,7 +16,7 @@ export default defineNuxtConfig({
'nuxt-auth-utils',
'@vueuse/nuxt',
'dayjs-nuxt',
- 'nuxt-mapbox'
+ 'nuxt-mapbox',
],
css: ['~/assets/css/tailwind.css'],
@@ -47,17 +47,17 @@ export default defineNuxtConfig({
},
colorMode: {
- preference: 'dark'
+ preference: 'dark',
},
dayjs: {
locales: ['zh-cn', 'en'],
- plugins: ['relativeTime', 'utc', 'timezone'],
+ plugins: ['relativeTime', 'utc', 'timezone', 'duration'],
defaultLocale: 'zh-cn',
- defaultTimezone: 'Asia/Shanghai'
+ defaultTimezone: 'Asia/Shanghai',
},
mapbox: {
- accessToken: process.env.MAPBOX_TOKEN || ''
+ accessToken: process.env.MAPBOX_TOKEN || '',
},
-})
\ No newline at end of file
+})
diff --git a/package.json b/package.json
index 11ab1228..b76bb0bd 100644
--- a/package.json
+++ b/package.json
@@ -22,6 +22,7 @@
},
"dependencies": {
"@aws-sdk/client-s3": "^3.873.0",
+ "@aws-sdk/s3-request-presigner": "^3.878.0",
"@chronoframe/webgl-image": "workspace:*",
"@nuxt/fonts": "0.11.4",
"@nuxt/icon": "2.0.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5735d746..68dd47f4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -11,6 +11,9 @@ importers:
'@aws-sdk/client-s3':
specifier: ^3.873.0
version: 3.873.0
+ '@aws-sdk/s3-request-presigner':
+ specifier: ^3.878.0
+ version: 3.878.0
'@chronoframe/webgl-image':
specifier: workspace:*
version: link:packages/webgl-image
@@ -266,6 +269,10 @@ packages:
resolution: {integrity: sha512-WrROjp8X1VvmnZ4TBzwM7RF+EB3wRaY9kQJLXw+Aes0/3zRjUXvGIlseobGJMqMEGnM0YekD2F87UaVfot1xeQ==}
engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-sVFBFkdoPOPyY13NaXO1E/R9O5J6ixzHnnRbqrbXYM2QQgLNPTKIiRtmVEuVoFV9YULg+/aKm7caix8m468y9w==}
+ engines: {node: '>=18.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-FWj1yUs45VjCADv80JlGshAttUHBL2xtTAbJcAxkkJZzLRKVkdyrepFWhv/95MvDyzfbT6PgJiWMdW65l/8ooA==}
engines: {node: '>=18.0.0'}
@@ -326,6 +333,10 @@ packages:
resolution: {integrity: sha512-bOoWGH57ORK2yKOqJMmxBV4b3yMK8Pc0/K2A98MNPuQedXaxxwzRfsT2Qw+PpfYkiijrrNFqDYmQRGntxJ2h8A==}
engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-h+TDs9EKAfXnrkogQpQz3o11zvs6Vh9+ehxyd35OcM7evnDeoV4GFjjnAKq+MxbBk/5Ewnvng+d6/WQDvMbj7Q==}
+ engines: {node: '>=18.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-AF55J94BoiuzN7g3hahy0dXTVZahVi8XxRBLgzNp6yQf0KTng+hb/V9UQZVYY1GZaDczvvvnqC54RGe9OZZ9zQ==}
engines: {node: '>=18.0.0'}
@@ -342,10 +353,18 @@ packages:
resolution: {integrity: sha512-q9sPoef+BBG6PJnc4x60vK/bfVwvRWsPgcoQyIra057S/QGjq5VkjvNk6H8xedf6vnKlXNBwq9BaANBXnldUJg==}
engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-i90yClfuaaPERnmCGb+yAmBtCrbHssIgVMQsnz9Q5RUBEcgRObKDAXe/pBQowEvNeObPYSUzgLjVHcv/FGhpyw==}
+ engines: {node: '>=18.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-FQ5OIXw1rmDud7f/VO9y2Mg9rX1o4MnngRKUOD8mS9ALK4uxKrTczb4jA+uJLSLwTqMGs3bcB1RzbMW1zWTMwQ==}
engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-OMDcuaVlC2rbze92w4QcNfuEA0IeT2GsT1ByZCwe+Y9tZwxzj7fCiOOU0UmJfa+juuQ/YBzVYxnkrkz3Rg6DEw==}
+ engines: {node: '>=18.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-BWOCeFeV/Ba8fVhtwUw/0Hz4wMm9fjXnMb4Z2a5he/jFlz5mt1/rr6IQ4MyKgzOaz24YrvqsJW2a0VUKOaYDvg==}
engines: {node: '>=18.0.0'}
@@ -362,6 +381,10 @@ packages:
resolution: {integrity: sha512-YByHrhjxYdjKRf/RQygRK1uh0As1FIi9+jXTcIEX/rBgN8mUByczr2u4QXBzw7ZdbdcOBMOkPnLRjNOWW1MkFg==}
engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-v//b9jFnhzTKKV3HFTw2MakdM22uBAs2lBov51BWmFXuFtSTdBLrR7zgfetQPE3PVkFai0cmtJQPdc3MX+T/cQ==}
+ engines: {node: '>=18.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-xcVhZF6svjM5Rj89T1WzkjQmrTF6dpR2UvIHPMTnSZoNe6CixejPZ6f0JJ2kAhO8H+dUHwNBlsUgOTIKiK/Syg==}
engines: {node: '>=18.0.0'}
@@ -7922,6 +7945,24 @@ snapshots:
fast-xml-parser: 5.2.5
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.862.0
+ '@aws-sdk/xml-builder': 3.873.0
+ '@smithy/core': 3.8.0
+ '@smithy/node-config-provider': 4.1.4
+ '@smithy/property-provider': 4.0.5
+ '@smithy/protocol-http': 5.1.3
+ '@smithy/signature-v4': 5.1.3
+ '@smithy/smithy-client': 4.4.10
+ '@smithy/types': 4.3.2
+ '@smithy/util-base64': 4.0.0
+ '@smithy/util-body-length-browser': 4.0.0
+ '@smithy/util-middleware': 4.0.5
+ '@smithy/util-utf8': 4.0.0
+ fast-xml-parser: 5.2.5
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/core': 3.873.0
@@ -8087,6 +8128,23 @@ snapshots:
'@smithy/util-utf8': 4.0.0
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.876.0
+ '@aws-sdk/types': 3.862.0
+ '@aws-sdk/util-arn-parser': 3.873.0
+ '@smithy/core': 3.8.0
+ '@smithy/node-config-provider': 4.1.4
+ '@smithy/protocol-http': 5.1.3
+ '@smithy/signature-v4': 5.1.3
+ '@smithy/smithy-client': 4.4.10
+ '@smithy/types': 4.3.2
+ '@smithy/util-config-provider': 4.0.0
+ '@smithy/util-middleware': 4.0.5
+ '@smithy/util-stream': 4.2.4
+ '@smithy/util-utf8': 4.0.0
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/types': 3.862.0
@@ -8155,6 +8213,17 @@ snapshots:
'@smithy/util-middleware': 4.0.5
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/signature-v4-multi-region': 3.876.0
+ '@aws-sdk/types': 3.862.0
+ '@aws-sdk/util-format-url': 3.873.0
+ '@smithy/middleware-endpoint': 4.1.18
+ '@smithy/protocol-http': 5.1.3
+ '@smithy/smithy-client': 4.4.10
+ '@smithy/types': 4.3.2
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/middleware-sdk-s3': 3.873.0
@@ -8164,6 +8233,15 @@ snapshots:
'@smithy/types': 4.3.2
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/middleware-sdk-s3': 3.876.0
+ '@aws-sdk/types': 3.862.0
+ '@smithy/protocol-http': 5.1.3
+ '@smithy/signature-v4': 5.1.3
+ '@smithy/types': 4.3.2
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/core': 3.873.0
@@ -8193,6 +8271,13 @@ snapshots:
'@smithy/util-endpoints': 3.0.7
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.862.0
+ '@smithy/querystring-builder': 4.0.5
+ '@smithy/types': 4.3.2
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
tslib: 2.8.1
diff --git a/server/api/photos/index.get.ts b/server/api/photos/index.get.ts
index fa74e723..f39cf077 100644
--- a/server/api/photos/index.get.ts
+++ b/server/api/photos/index.get.ts
@@ -1,12 +1,9 @@
-import { StorageObject } from '~~/server/services/storage'
-import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+import { desc } from 'drizzle-orm'
-export default eventHandler(async (event) => {
- // const { storageProvider } = useStorageProvider(event)
- // const photos = await storageProvider.listAll()
- // return {
- // urls: photos.map((photo) => storageProvider.getPublicUrl(photo.key)),
- // objects: photos as StorageObject[],
- // }
- return await useDB().select().from(tables.photos).orderBy(tables.photos.dateTaken).all()
+export default eventHandler(async (_event) => {
+ return useDB()
+ .select()
+ .from(tables.photos)
+ .orderBy(desc(tables.photos.dateTaken))
+ .all()
})
diff --git a/server/api/photos/index.post.ts b/server/api/photos/index.post.ts
new file mode 100644
index 00000000..20e76770
--- /dev/null
+++ b/server/api/photos/index.post.ts
@@ -0,0 +1,51 @@
+import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+
+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 body = await readBody(event)
+ const { fileName, contentType } = body
+
+ if (!fileName) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: 'fileName is required',
+ })
+ }
+
+ try {
+ // 生成唯一的文件名,使用时间戳前缀避免冲突
+ const uniqueFileName = `${fileName}`
+
+ // 获取预签名 URL,设置1小时过期时间
+ const signedUrl = await storageProvider.getSignedUrl(
+ uniqueFileName,
+ 3600, // 1小时过期
+ {
+ contentType: contentType || 'application/octet-stream',
+ }
+ )
+
+ return {
+ signedUrl,
+ fileKey: uniqueFileName,
+ expiresIn: 3600,
+ }
+ } catch (error) {
+ logger.chrono.error('Failed to generate signed URL:', error)
+ throw createError({
+ statusCode: 500,
+ statusMessage: 'Failed to generate signed URL',
+ })
+ }
+})
\ No newline at end of file
diff --git a/server/api/photos/process.post.ts b/server/api/photos/process.post.ts
new file mode 100644
index 00000000..6fa0793f
--- /dev/null
+++ b/server/api/photos/process.post.ts
@@ -0,0 +1,76 @@
+import { execPhotoPipelineAsync } from '~~/server/services/photo/pipeline-async'
+import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+
+export default eventHandler(async (event) => {
+ await requireUserSession(event)
+
+ const { storageProvider } = useStorageProvider(event)
+ const body = await readBody(event)
+ const { fileKey, fileName, fileSize } = body
+
+ if (!fileKey) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: 'fileKey is required',
+ })
+ }
+
+ try {
+ // 验证文件是否存在于存储中
+ const fileBuffer = await storageProvider.get(fileKey)
+ if (!fileBuffer) {
+ throw createError({
+ statusCode: 404,
+ statusMessage: 'File not found in storage',
+ })
+ }
+
+ // 创建存储对象信息
+ const originalObject = {
+ key: fileKey,
+ size: fileSize || fileBuffer.length,
+ lastModified: new Date(),
+ }
+
+ logger.chrono.info('Starting photo processing for', fileKey)
+
+ // 异步处理照片
+ processPhotoInBackground(fileKey, originalObject, fileName)
+
+ return {
+ message: 'Photo processing started',
+ fileKey,
+ status: 'processing'
+ }
+ } catch (error) {
+ logger.chrono.error('Failed to start photo processing:', error)
+ throw createError({
+ statusCode: 500,
+ statusMessage: 'Failed to start photo processing',
+ })
+ }
+})
+
+// 后台处理函数
+async function processPhotoInBackground(s3key: string, originalObject: any, originalFileName?: string) {
+ try {
+ logger.chrono.info('Starting background photo processing for', s3key)
+
+ const photo = await execPhotoPipelineAsync(s3key, originalObject)
+
+ if (!photo) {
+ logger.chrono.error('Photo processing failed for', s3key)
+ return
+ }
+
+ // 如果有原始文件名,使用它作为标题
+ if (originalFileName && !photo.title) {
+ photo.title = originalFileName
+ }
+
+ await useDB().insert(tables.photos).values(photo).execute()
+ logger.chrono.success('Background photo processing completed for', photo.title || photo.storageKey)
+ } catch (error) {
+ logger.chrono.error('Background photo processing error for', s3key, error)
+ }
+}
diff --git a/server/services/storage/interfaces.ts b/server/services/storage/interfaces.ts
index cd4ea789..de53a82d 100644
--- a/server/services/storage/interfaces.ts
+++ b/server/services/storage/interfaces.ts
@@ -33,7 +33,10 @@ export type GitHubStorageConfig = {
token?: string
}
-export type StorageConfig = S3StorageConfig | HubR2StorageConfig | GitHubStorageConfig
+export type StorageConfig =
+ | S3StorageConfig
+ | HubR2StorageConfig
+ | GitHubStorageConfig
export interface UploadOptions {
contentType?: string
@@ -51,6 +54,11 @@ export interface StorageProvider {
delete(key: string): Promise<void>
get(key: string): Promise<Buffer | null>
getPublicUrl(key: string): string
+ getSignedUrl?(
+ key: string,
+ expiresIn?: number,
+ options?: UploadOptions,
+ ): Promise<string>
listAll(): Promise<StorageObject[]>
listImages(): Promise<StorageObject[]>
}
diff --git a/server/services/storage/providers/s3.ts b/server/services/storage/providers/s3.ts
index 2040efe8..016547f0 100644
--- a/server/services/storage/providers/s3.ts
+++ b/server/services/storage/providers/s3.ts
@@ -7,6 +7,7 @@ import {
S3Client,
S3ClientConfig,
} from '@aws-sdk/client-s3'
+import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import {
S3StorageConfig,
StorageObject,
@@ -58,7 +59,11 @@ export class S3StorageProvider implements StorageProvider {
this.client = createClient(config)
}
- async create(key: string, data: Buffer, contentType?: string): Promise<StorageObject> {
+ async create(
+ key: string,
+ data: Buffer,
+ contentType?: string,
+ ): Promise<StorageObject> {
try {
const cmd = new PutObjectCommand({
Bucket: this.config.bucket,
@@ -68,7 +73,7 @@ export class S3StorageProvider implements StorageProvider {
})
const resp = await this.client.send(cmd)
-
+
this.logger?.success(`Created object with key: ${key}`)
return {
@@ -152,14 +157,23 @@ export class S3StorageProvider implements StorageProvider {
return `${endpoint.replace(/\/+$/, '')}/${key}`
}
- async getPresignedUploadUrl(
+ async getSignedUrl(
key: string,
- expiresIn?: number,
+ expiresIn: number = 3600,
options?: UploadOptions,
- ): Promise<{ url: string }> {
- // TODO: Implement presigned URL generation
- // This requires @aws-sdk/s3-request-presigner package
- throw new Error('Presigned upload URL generation not implemented. Please install @aws-sdk/s3-request-presigner and implement this method.')
+ ): Promise<string> {
+ const cmd = new PutObjectCommand({
+ Bucket: this.config.bucket,
+ Key: key,
+ ContentType: options?.contentType || 'application/octet-stream',
+ })
+
+ const url = await getSignedUrl(this.client, cmd, {
+ expiresIn,
+ // 为了更好的 CORS 支持,添加一些额外参数
+ unhoistableHeaders: new Set(['Content-Type']),
+ })
+ return url
}
async listAll(): Promise<StorageObject[]> {