Improve SFTP file view and upload handling

Add hidden-file toggle and search, prevent rapid-click path duplication, fix multipart upload headers, and raise backend upload size limits with clearer errors.
This commit is contained in:
liumangmang
2026-03-10 18:07:51 +08:00
parent 939b2ff287
commit 8845847ce2
5 changed files with 223 additions and 133 deletions

View File

@@ -0,0 +1,42 @@
package com.sshmanager.exception;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity<Map<String, String>> handleMaxUploadSize(MaxUploadSizeExceededException e) {
Map<String, String> err = new HashMap<>();
err.put("error", "上传失败:文件大小超过限制");
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(err);
}
@ExceptionHandler(MultipartException.class)
public ResponseEntity<Map<String, String>> handleMultipart(MultipartException e) {
Throwable root = e;
while (root.getCause() != null && root.getCause() != root) {
root = root.getCause();
}
if (root instanceof FileSizeLimitExceededException
|| (root.getMessage() != null && root.getMessage().contains("exceeds its maximum permitted size"))) {
Map<String, String> err = new HashMap<>();
err.put("error", "上传失败:文件大小超过限制");
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(err);
}
Map<String, String> err = new HashMap<>();
err.put("error", "上传失败:表单解析异常");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(err);
}
}

View File

@@ -5,6 +5,10 @@ spring:
web: web:
resources: resources:
add-mappings: false # 使用 SpaForwardConfig 统一处理静态与 SPA 回退 add-mappings: false # 使用 SpaForwardConfig 统一处理静态与 SPA 回退
servlet:
multipart:
max-file-size: 200MB
max-request-size: 200MB
datasource: datasource:
url: jdbc:h2:file:./data/sshmanager;DB_CLOSE_DELAY=-1 url: jdbc:h2:file:./data/sshmanager;DB_CLOSE_DELAY=-1
driver-class-name: org.h2.Driver driver-class-name: org.h2.Driver

View File

@@ -12,6 +12,19 @@ client.interceptors.request.use((config) => {
if (token) { if (token) {
config.headers.Authorization = `Bearer ${token}` config.headers.Authorization = `Bearer ${token}`
} }
// Let the browser set the correct multipart boundary.
if (typeof FormData !== 'undefined' && config.data instanceof FormData) {
const headers: any = config.headers ?? {}
if (typeof headers.set === 'function') {
headers.set('Content-Type', undefined)
} else {
delete headers['Content-Type']
delete headers['content-type']
}
config.headers = headers
}
return config return config
}) })

View File

@@ -39,10 +39,9 @@ export async function downloadFile(connectionId: number, path: string) {
export function uploadFile(connectionId: number, path: string, file: File) { export function uploadFile(connectionId: number, path: string, file: File) {
const form = new FormData() const form = new FormData()
form.append('file', file) form.append('file', file, file.name)
return client.post('/sftp/upload', form, { return client.post('/sftp/upload', form, {
params: { connectionId, path }, params: { connectionId, path },
headers: { 'Content-Type': 'multipart/form-data' },
}) })
} }

View File

@@ -11,6 +11,8 @@ import {
Upload, Upload,
FolderPlus, FolderPlus,
RefreshCw, RefreshCw,
Eye,
EyeOff,
Download, Download,
Trash2, Trash2,
ChevronRight, ChevronRight,
@@ -33,6 +35,15 @@ const uploading = ref(false)
const selectedFile = ref<string | null>(null) const selectedFile = ref<string | null>(null)
const fileInputRef = ref<HTMLInputElement | null>(null) const fileInputRef = ref<HTMLInputElement | null>(null)
const showHiddenFiles = ref(false)
const searchQuery = ref('')
const filteredFiles = computed(() => {
const q = searchQuery.value.trim().toLowerCase()
const base = showHiddenFiles.value ? files.value : files.value.filter((f) => !f.name.startsWith('.'))
if (!q) return base
return base.filter((f) => f.name.toLowerCase().includes(q))
})
const showTransferModal = ref(false) const showTransferModal = ref(false)
const transferFile = ref<SftpFileInfo | null>(null) const transferFile = ref<SftpFileInfo | null>(null)
const transferTargetConnectionId = ref<number | null>(null) const transferTargetConnectionId = ref<number | null>(null)
@@ -86,6 +97,7 @@ function loadPath() {
} }
function navigateToDir(name: string) { function navigateToDir(name: string) {
if (loading.value) return
const base = currentPath.value === '.' || currentPath.value === '' ? '' : currentPath.value const base = currentPath.value === '.' || currentPath.value === '' ? '' : currentPath.value
currentPath.value = base ? (base.endsWith('/') ? base + name : base + '/' + name) : name currentPath.value = base ? (base.endsWith('/') ? base + name : base + '/' + name) : name
pathParts.value = currentPath.value === '/' ? [''] : currentPath.value.split('/').filter(Boolean) pathParts.value = currentPath.value === '/' ? [''] : currentPath.value.split('/').filter(Boolean)
@@ -93,6 +105,7 @@ function navigateToDir(name: string) {
} }
function navigateToIndex(i: number) { function navigateToIndex(i: number) {
if (loading.value) return
if (i < 0) { if (i < 0) {
currentPath.value = '.' currentPath.value = '.'
} else { } else {
@@ -103,6 +116,7 @@ function navigateToIndex(i: number) {
} }
function goUp() { function goUp() {
if (loading.value) return
if (currentPath.value === '.' || currentPath.value === '' || currentPath.value === '/') { if (currentPath.value === '.' || currentPath.value === '' || currentPath.value === '/') {
return return
} }
@@ -153,8 +167,9 @@ async function handleFileSelect(e: Event) {
await sftpApi.uploadFile(connectionId.value, path, file) await sftpApi.uploadFile(connectionId.value, path, file)
} }
loadPath() loadPath()
} catch { } catch (err: unknown) {
error.value = '上传失败' const res = err as { response?: { data?: { error?: string } } }
error.value = res?.response?.data?.error ?? '上传失败'
} finally { } finally {
uploading.value = false uploading.value = false
input.value = '' input.value = ''
@@ -254,8 +269,8 @@ function formatDate(ts: number): string {
<div class="flex-1 overflow-auto p-4"> <div class="flex-1 overflow-auto p-4">
<div class="bg-slate-800 rounded-xl border border-slate-700 overflow-hidden"> <div class="bg-slate-800 rounded-xl border border-slate-700 overflow-hidden">
<div class="flex items-center gap-2 p-3 border-b border-slate-700 bg-slate-800/80"> <div class="flex flex-col sm:flex-row sm:items-center gap-2 p-3 border-b border-slate-700 bg-slate-800/80">
<nav class="flex items-center gap-1 text-sm text-slate-400 min-w-0 flex-1"> <nav class="flex items-center gap-1 text-sm text-slate-400 min-w-0 w-full sm:flex-1">
<button <button
@click="navigateToIndex(-1)" @click="navigateToIndex(-1)"
class="px-2 py-1 rounded hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer truncate" class="px-2 py-1 rounded hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer truncate"
@@ -272,7 +287,24 @@ function formatDate(ts: number): string {
</button> </button>
</template> </template>
</nav> </nav>
<div class="flex items-center gap-1 flex-shrink-0"> <div class="w-full sm:w-auto flex items-center gap-2 justify-end">
<div class="flex-1 sm:flex-none">
<input
v-model="searchQuery"
type="text"
class="w-full sm:w-56 rounded-lg border border-slate-600 bg-slate-900/30 px-3 py-2 text-sm text-slate-100 placeholder-slate-500 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
placeholder="搜索文件..."
aria-label="搜索文件"
/>
</div>
<button
@click="showHiddenFiles = !showHiddenFiles"
class="p-2 rounded-lg text-slate-400 hover:bg-slate-700 hover:text-slate-100 transition-colors duration-200 cursor-pointer"
:aria-label="showHiddenFiles ? '隐藏隐藏文件' : '显示隐藏文件'"
:title="showHiddenFiles ? '隐藏隐藏文件' : '显示隐藏文件'"
>
<component :is="showHiddenFiles ? EyeOff : Eye" class="w-4 h-4" aria-hidden="true" />
</button>
<button <button
@click="triggerUpload" @click="triggerUpload"
:disabled="uploading" :disabled="uploading"
@@ -322,10 +354,10 @@ function formatDate(ts: number): string {
<span class="text-slate-400">..</span> <span class="text-slate-400">..</span>
</button> </button>
<button <button
v-for="file in files" v-for="file in filteredFiles"
:key="file.name" :key="file.name"
@click="handleFileClick(file)" @click="handleFileClick(file)"
@dblclick="file.directory ? navigateToDir(file.name) : handleDownload(file)" @dblclick="!file.directory && handleDownload(file)"
class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-700/50 transition-colors duration-200 cursor-pointer text-left group" class="w-full flex items-center gap-3 px-4 py-3 hover:bg-slate-700/50 transition-colors duration-200 cursor-pointer text-left group"
> >
<component <component
@@ -364,8 +396,8 @@ function formatDate(ts: number): string {
</button> </button>
</div> </div>
</button> </button>
<div v-if="files.length === 0 && !loading" class="p-8 text-center text-slate-500"> <div v-if="filteredFiles.length === 0 && !loading" class="p-8 text-center text-slate-500">
空目录 {{ files.length === 0 ? '空目录' : (searchQuery.trim() ? '未找到匹配文件' : '无可见文件已隐藏隐藏文件') }}
</div> </div>
</div> </div>
</div> </div>