Merge pull request #108 from mvanhorn/feat/107-zip-download

feat: add zip download for folders in the file manager
This commit is contained in:
engigu
2026-06-03 17:56:41 +08:00
committed by GitHub
8 changed files with 184 additions and 4 deletions
+48
View File
@@ -5,6 +5,7 @@ import (
"os"
"path/filepath"
"strings"
"time"
"github.com/engigu/baihu-panel/internal/utils"
@@ -492,3 +493,50 @@ func (fc *FileController) DownloadFile(c *gin.Context) {
c.Header("Content-Type", "application/octet-stream")
c.File(fullPath)
}
func (fc *FileController) DownloadZip(c *gin.Context) {
paths := c.QueryArray("path")
if len(paths) == 0 || c.ContentType() == "application/json" {
var req struct {
Paths []string `json:"paths"`
}
if err := c.ShouldBindJSON(&req); err == nil && len(paths) == 0 {
paths = req.Paths
}
}
if len(paths) == 0 {
utils.BadRequest(c, "path参数必填")
return
}
validatedAbsPaths := make([]string, 0, len(paths))
for _, path := range paths {
fullPath, safe := fc.checkPath(path, false)
if !safe {
utils.Forbidden(c, "访问被拒绝")
return
}
if _, err := os.Stat(fullPath); err != nil {
utils.NotFound(c, "文件不存在")
return
}
validatedAbsPaths = append(validatedAbsPaths, fullPath)
}
fileName := "baihu-export-" + time.Now().Format("20060102-150405") + ".zip"
if len(validatedAbsPaths) == 1 {
fileName = filepath.Base(validatedAbsPaths[0]) + ".zip"
}
c.Header("Content-Description", "File Transfer")
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Content-Disposition", "attachment; filename="+fileName)
c.Header("Content-Type", "application/zip")
if err := utils.CreateZip(c.Writer, validatedAbsPaths); err != nil {
return
}
}
+1
View File
@@ -129,6 +129,7 @@ func registerFileRoutes(g *gin.RouterGroup, c *Controllers) {
files.GET("/tree", c.File.GetFileTree)
files.GET("/content", c.File.GetFileContent)
files.GET("/download", c.File.DownloadFile)
files.GET("/download-zip", c.File.DownloadZip)
files.POST("/content", c.File.SaveFileContent)
files.POST("/create", c.File.CreateFile)
files.POST("/delete", c.File.DeleteFile)
+98
View File
@@ -5,11 +5,109 @@ import (
"archive/zip"
"compress/gzip"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
)
func CreateZip(dst io.Writer, basePaths []string) (err error) {
w := zip.NewWriter(dst)
defer func() {
if closeErr := w.Close(); err == nil {
err = closeErr
}
}()
for _, basePath := range basePaths {
info, err := os.Lstat(basePath)
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
continue
}
if info.Mode().IsRegular() {
if err := addZipFile(w, basePath, filepath.Base(basePath), info); err != nil {
return err
}
continue
}
if info.IsDir() {
baseName := filepath.Base(basePath)
if err := filepath.WalkDir(basePath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.Type()&fs.ModeSymlink != 0 {
return nil
}
rel, err := filepath.Rel(basePath, path)
if err != nil || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || rel == ".." {
return nil
}
name := baseName
if rel != "." {
name = filepath.Join(baseName, rel)
}
name = filepath.ToSlash(name)
info, err := d.Info()
if err != nil {
return err
}
if d.IsDir() {
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = name + "/"
_, err = w.CreateHeader(header)
return err
}
if info.Mode().IsRegular() {
return addZipFile(w, path, name, info)
}
return nil
}); err != nil {
return err
}
}
}
return nil
}
func addZipFile(w *zip.Writer, path, name string, info os.FileInfo) error {
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = filepath.ToSlash(name)
header.Method = zip.Deflate
writer, err := w.CreateHeader(header)
if err != nil {
return err
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
}
func ExtractZip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
+1 -1
View File
@@ -192,6 +192,7 @@ export const api = {
tree: () => request<FileNode[]>('/files/tree'),
getContent: (path: string) => request<{ path: string; content: string }>(`/files/content?path=${encodeURIComponent(path)}`),
download: (path: string) => `${API_BASE_URL}/files/download?path=${encodeURIComponent(path)}`,
downloadZip: (path: string) => `${API_BASE_URL}/files/download-zip?path=${encodeURIComponent(path)}`,
saveContent: (path: string, content: string) => request('/files/content', { method: 'POST', body: JSON.stringify({ path, content }) }),
create: (path: string, isDir: boolean) => request('/files/create', { method: 'POST', body: JSON.stringify({ path, isDir }) }),
delete: (path: string) => request('/files/delete', { method: 'POST', body: JSON.stringify({ path }) }),
@@ -725,4 +726,3 @@ export const LOG_STATUS = {
FAILED: 'failed'
} as const
+8 -2
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Folder, File, ChevronRight, ChevronDown, Trash2, Copy as CopyIcon } from 'lucide-vue-next'
import { Folder, File, ChevronRight, ChevronDown, Trash2, Copy as CopyIcon, Download } from 'lucide-vue-next'
import type { FileNode } from '@/api'
defineOptions({
@@ -21,6 +21,7 @@ const emit = defineEmits<{
move: [oldPath: string, newPath: string]
rename: [path: string]
downloadFile: [path: string]
downloadZip: [path: string]
duplicate: [path: string]
}>()
@@ -100,6 +101,10 @@ function handleDrop(e: DragEvent) {
</div>
<div v-else
class="opacity-0 group-hover:opacity-100 flex items-center gap-1 ml-auto shrink-0 pr-1 transition-opacity">
<span @click.stop="$emit('downloadZip', node.path)" class="cursor-pointer text-blue-500 hover:text-blue-500/80"
title="下载为压缩包">
<Download class="h-3 w-3" />
</span>
<span @click.stop="$emit('delete', node.path)" class="cursor-pointer text-destructive hover:text-destructive/80"
title="删除">
<Trash2 class="h-3 w-3" />
@@ -111,7 +116,8 @@ function handleDrop(e: DragEvent) {
:selected-path="selectedPath" :depth="depth + 1" @select="$emit('select', $event)"
@create="$emit('create', $event)" @move="(oldPath, newPath) => $emit('move', oldPath, newPath)"
@rename="$emit('rename', $event)" @delete="$emit('delete', $event)"
@download-file="$emit('downloadFile', $event)" @duplicate="$emit('duplicate', $event)" />
@download-file="$emit('downloadFile', $event)" @download-zip="$emit('downloadZip', $event)"
@duplicate="$emit('duplicate', $event)" />
</template>
</div>
</template>
+10
View File
@@ -297,6 +297,15 @@ async function handleDownload(path: string) {
toast.success('下载中')
}
async function handleDownloadZip(path: string) {
const url = api.files.downloadZip(path)
const a = document.createElement('a')
a.href = url
a.download = (path.split('/').pop() || 'archive') + '.zip'
a.click()
toast.success('下载中')
}
async function handleCopyFile(path: string) {
try {
const parts = path.split('/')
@@ -466,6 +475,7 @@ onUnmounted(() => {
@delete="(path: string) => dialogsRef?.openDelete(path)"
@create="(parent: string) => dialogsRef?.openCreate(parent)"
@download="handleDownload"
@download-zip="handleDownloadZip"
@move="handleMove"
@rename="(path: string) => dialogsRef?.openRename(path)"
@duplicate="handleCopyFile"
@@ -19,6 +19,7 @@ const emit = defineEmits<{
select: [node: FileNode]
delete: [path: string]
download: [path: string]
downloadZip: [path: string]
move: [oldPath: string, newPath: string]
rename: [path: string]
duplicate: [path: string]
@@ -158,6 +159,7 @@ function handleFilesUpload(e: Event) {
@delete="p => emit('delete', p)"
@create="p => emit('create', p)"
@download-file="p => emit('download', p)"
@download-zip="p => emit('downloadZip', p)"
@move="(o, n) => emit('move', o, n)"
@rename="p => emit('rename', p)"
@duplicate="p => emit('duplicate', p)" />
+16 -1
View File
@@ -267,6 +267,21 @@ async function handleDownload(path: string) {
}
}
async function handleDownloadZip(path: string) {
try {
const url = api.files.downloadZip(path)
const a = document.createElement('a')
a.href = url
a.download = (path.split('/').pop() || 'archive') + '.zip'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
toast.success('已发起下载')
} catch (error: any) {
toast.error('下载出错: ' + (error.message || '未知错误'))
}
}
async function handleCopyFile(path: string) {
console.log('Copy file requested:', path)
try {
@@ -320,7 +335,7 @@ onMounted(loadTree)
</div>
<FileTreeNode v-for="node in fileTree" :key="node.path" :node="node" :expanded-dirs="expandedDirs"
:selected-path="selectedFile || selectedDir" @select="handleSelect" @delete="confirmDeleteFile"
@download-file="handleDownload" @duplicate="handleCopyFile" />
@download-file="handleDownload" @download-zip="handleDownloadZip" @duplicate="handleCopyFile" />
</div>
</div>