Skip to content

Commit

Permalink
fix(update-file-donwlaoder-UI): Updated file download to be in list i…
Browse files Browse the repository at this point in the history
…tem ,updated dilaog for download and updated api path formation
  • Loading branch information
priyakanabar-crest authored and Carson-Shaar committed Nov 21, 2024
1 parent 8fd52dd commit 87cbbdc
Show file tree
Hide file tree
Showing 3 changed files with 339 additions and 151 deletions.
46 changes: 19 additions & 27 deletions zt_backend/router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import shutil
from fastapi import (
APIRouter,
Depends,
WebSocket,
WebSocketDisconnect,
Query,
Expand Down Expand Up @@ -683,68 +684,59 @@ def delete_item(delete_request: request.DeleteItemRequest):

@router.get("/api/download")
async def download_item(
request: Request,
path: str,
filename: str,
isFolder: bool,
chunk_size: int = 8192
request: Request, # For headers
download_req: request.DownloadRequest = Depends() # This is the key change
):
"""Stream download with range support and error handling for both files and folders."""
"""Stream download with range support for files and folders."""
try:
file_path = Path(path)
validate_path(file_path, filename)
chunk_size: int = 8192
file_path = Path(download_req.path).resolve()

if not file_path.exists():
raise HTTPException(status_code=404, detail="Path not found")

if isFolder:
# Create a temporary zip file
if download_req.isFolder:
with tempfile.NamedTemporaryFile(delete=False, suffix='.zip') as temp_zip:
temp_zip_path = temp_zip.name

# Create a zip file containing the folder contents

await create_zip_file(file_path, temp_zip_path)
file_path = Path(temp_zip_path)
filename = f"{filename}.zip"
elif not file_path.is_file():
raise HTTPException(status_code=400, detail=f"The path specified is not a file: {filename}")
download_req.filename = f"{download_req.filename}.zip"

file_size = file_path.stat().st_size
start, end = await parse_range_header(
request.headers.get('range'),
file_size
)

# Create response with proper headers
response = StreamingResponse(
stream_file_range(str(file_path), start, end, chunk_size),
status_code=206 if request.headers.get('range') else 200,
media_type=get_mime_type(filename)
media_type=get_mime_type(download_req.filename)
)

# Set headers
response.headers.update({
"Content-Range": f"bytes {start}-{end}/{file_size}",
"Content-Length": str(end - start + 1),
"Content-Disposition": f"attachment; filename={filename}",
"Accept-Ranges": "bytes",
"Cache-Control": "no-cache",
"Content-Encoding": "identity"
"Content-Disposition": f"attachment; filename={download_req.filename}",
"Accept-Ranges": "bytes"
})

if isFolder:
# Clean up the temporary zip file after streaming
if download_req.isFolder:
async def cleanup_temp_file():
yield
os.unlink(temp_zip_path)

response.background = cleanup_temp_file()

return response

except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Download failed: {str(e)}"
detail=str(e)
)



@router.get("/api/get_files")
def list_files():
path = Path(".")
Expand Down
30 changes: 9 additions & 21 deletions zt_frontend/src/components/FileExplorer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
<v-list-item-title @click="handleItemClick(item)" :class="{'clickable-item': item.file === 'folder'}">{{ item.title }}</v-list-item-title>

<template v-slot:append>
<v-menu>
<v-menu v-if="!isProtectedFile(item.title)" :close-on-content-click="false">
<template v-slot:activator="{ props }">
<v-btn
icon
Expand All @@ -54,13 +54,13 @@
</v-btn>
</template>
<v-list>
<v-list-item
@click="openDownloadDialog(item)"
>
<v-list-item-title>
<v-icon size="small" class="mr-2">mdi-download</v-icon>
Download
</v-list-item-title>
<v-list-item>
<FileFolderDownloadDialog
:current-path="currentPath"
:title="item.title"
:file="item.file"
@file-downloaded="refreshFiles"
/>
</v-list-item>
<v-list-item v-if="!isProtectedFile(item.title)" @click="openRenameDialog(item)">
<v-list-item-title>Rename</v-list-item-title>
Expand Down Expand Up @@ -92,11 +92,6 @@
</template>
</v-snackbar>

<FileFolderDownloadDialog
ref="downloadDialog"
:current-path="currentPath"
@file-downloaded="refreshFiles"
/>

<RenameDialog
ref="renameDialog"
Expand Down Expand Up @@ -163,14 +158,9 @@ export default defineComponent({
return protectedFiles.value.includes(filename);
};
const downloadDialog = ref<InstanceType<typeof FileFolderDownloadDialog> | null>(null);
const renameDialog = ref<InstanceType<typeof RenameDialog> | null>(null);
const deleteDialog = ref<InstanceType<typeof DeleteDialog> | null>(null);
const openDownloadDialog = (item: any) => {
downloadDialog.value?.openDialog(item);
};
const openRenameDialog = (item: any) => {
renameDialog.value?.openDialog(item);
};
Expand Down Expand Up @@ -270,8 +260,6 @@ export default defineComponent({
fileIcon,
newItemName,
itemTypes,
downloadDialog,
openDownloadDialog,
renameDialog,
openRenameDialog,
openDeleteDialog,
Expand Down
Loading

0 comments on commit 87cbbdc

Please sign in to comment.