feat(images): support uploading local ISO/vztmpl files to node storage
Some checks failed
Deploy to Production / Trigger production update (push) Has been cancelled
Backend Tests / pytest (Python 3.12) (push) Has been cancelled

Adds a local file upload path alongside the existing URL download flow:
a new /images/upload endpoint streams the file to a temp path and hands
it to a background worker that proxies it into Proxmox storage via the
upload API (requests-toolbelt handles the large multipart stream). Also
adds /images/resolve-filename to recover the real filename (Content-
Disposition) for URL-based downloads with opaque paths.

Raise nginx client_max_body_size and timeouts on both the frontend proxy
and the standalone nginx configs so multi-GB ISOs don't get cut off.
This commit is contained in:
markmorado
2026-07-24 06:17:46 +05:00
parent 8b4c8c3a30
commit 99d8ce750d
13 changed files with 533 additions and 52 deletions

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { Loader2, Download } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Loader2, Download, Upload, Wand2, FileUp, X } from 'lucide-react';
import {
Dialog,
DialogContent,
@@ -18,7 +18,14 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useImageStorages, useDownloadImage } from '@/hooks/use-image-catalog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
import {
useImageStorages,
useDownloadImage,
useUploadImageFile,
useResolveFilename,
} from '@/hooks/use-image-catalog';
import { useDeployTasksStore } from '@/stores/deploy-tasks-store';
import { toast } from 'sonner';
@@ -43,20 +50,32 @@ function fmtSize(bytes?: number): string {
return `${gb.toFixed(0)} GB`;
}
/** Имя файла из URL: хвост пути без query-строки. */
/** Размер выбранного локального файла: MB до 1 GB, иначе GB. */
function fmtFileSize(bytes: number): string {
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
}
/** Имя файла из URL: хвост пути без query-строки (грубая догадка на лету). */
function filenameFromUrl(url: string): string {
const path = url.split('?')[0].split('#')[0];
return path.split('/').pop() || '';
}
type Mode = 'url' | 'local';
export default function DownloadIsoDialog({ open, onClose, serverId, node, source }: Props) {
const fromMirror = !!source?.source_id;
const [mode, setMode] = useState<Mode>('url');
const [url, setUrl] = useState('');
const [filename, setFilename] = useState('');
const [storage, setStorage] = useState('');
const [checksum, setChecksum] = useState('');
const [checksumAlgo, setChecksumAlgo] = useState('sha256');
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [isDragging, setIsDragging] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { data: storages = [], isLoading: storagesLoading } = useImageStorages(
open ? serverId : undefined,
@@ -65,14 +84,19 @@ export default function DownloadIsoDialog({ open, onClose, serverId, node, sourc
);
const download = useDownloadImage(serverId);
const uploadFile = useUploadImageFile(serverId);
const resolveFilename = useResolveFilename();
const addDeployTask = useDeployTasksStore((s) => s.addTask);
useEffect(() => {
if (!open) return;
setMode('url');
setUrl(source?.url ?? '');
setFilename(source?.url ? filenameFromUrl(source.url) : '');
setChecksum('');
setChecksumAlgo('sha256');
setSelectedFile(null);
setIsDragging(false);
}, [open, source?.url]);
useEffect(() => {
@@ -81,11 +105,67 @@ export default function DownloadIsoDialog({ open, onClose, serverId, node, sourc
// Пользователь мог не тронуть имя — тогда ведём его за URL.
const effectiveFilename = filename.trim() || filenameFromUrl(url);
const isPending = download.isPending || uploadFile.isPending;
const submitDisabled =
!storage || download.isPending || (!fromMirror && (!url.trim() || !effectiveFilename));
!storage || isPending ||
(fromMirror ? false : mode === 'url' ? (!url.trim() || !effectiveFilename) : !selectedFile);
const handleDetectFilename = () => {
const trimmed = url.trim();
if (!trimmed) return;
resolveFilename.mutate(trimmed, {
onSuccess: (data) => {
if (data.filename) setFilename(data.filename);
else toast.error('Не удалось определить имя файла');
},
onError: (e: Error) => toast.error(e.message),
});
};
const pickFile = (file: File | undefined | null) => {
if (!file) return;
setSelectedFile(file);
};
const onSuccess = (data: { task_id: number; status: string; name: string }, msg: string) => {
addDeployTask({
id: data.task_id,
name: data.name,
status: 'pending',
step: 'В очереди...',
progress: 0,
vmid: null,
node,
error_message: null,
kind: mode === 'local' ? 'image_upload' : 'image_download',
server_id: serverId,
});
toast.success(msg);
onClose();
};
const submit = () => {
if (submitDisabled) return;
if (mode === 'local' && !fromMirror) {
if (!selectedFile) return;
uploadFile.mutate(
{
node,
storage,
content: 'iso',
file: selectedFile,
checksum: checksum.trim() || undefined,
checksum_algorithm: checksum.trim() ? checksumAlgo : undefined,
},
{
onSuccess: (data) => onSuccess(data, 'Загрузка ISO на ноду запущена в фоне'),
onError: (e: Error) => toast.error(e.message),
},
);
return;
}
download.mutate(
{
node,
@@ -98,22 +178,7 @@ export default function DownloadIsoDialog({ open, onClose, serverId, node, sourc
checksum_algorithm: checksum.trim() ? checksumAlgo : undefined,
},
{
onSuccess: (data) => {
addDeployTask({
id: data.task_id,
name: data.name,
status: 'pending',
step: 'В очереди...',
progress: 0,
vmid: null,
node,
error_message: null,
kind: 'image_download',
server_id: serverId,
});
toast.success('Загрузка ISO запущена в фоне');
onClose();
},
onSuccess: (data) => onSuccess(data, 'Загрузка ISO запущена в фоне'),
onError: (e: Error) => toast.error(e.message),
},
);
@@ -125,7 +190,11 @@ export default function DownloadIsoDialog({ open, onClose, serverId, node, sourc
<DialogHeader>
<DialogTitle>Загрузить ISO</DialogTitle>
<DialogDescription>
{fromMirror ? source?.name : 'Proxmox скачает образ по ссылке прямо на ноду'}
{fromMirror
? source?.name
: mode === 'local'
? 'Файл будет передан на ноду через панель'
: 'Proxmox скачает образ по ссылке прямо на ноду'}
</DialogDescription>
</DialogHeader>
@@ -135,29 +204,105 @@ export default function DownloadIsoDialog({ open, onClose, serverId, node, sourc
</div>
{!fromMirror && (
<>
<div>
<Label htmlFor="iso-url">URL образа</Label>
<Input
id="iso-url"
placeholder="https://releases.example.org/linux-24.04-amd64.iso"
value={url}
onChange={(e) => setUrl(e.target.value)}
<Tabs value={mode} onValueChange={(v) => v && setMode(v as Mode)}>
<TabsList className="w-full">
<TabsTrigger value="url" className="flex-1">
<Download className="mr-1.5 h-4 w-4" />По ссылке (URL)
</TabsTrigger>
<TabsTrigger value="local" className="flex-1">
<FileUp className="mr-1.5 h-4 w-4" />Локальный файл
</TabsTrigger>
</TabsList>
<TabsContent value="url" className="mt-4 space-y-4">
<div>
<Label htmlFor="iso-url">URL образа</Label>
<div className="flex gap-2">
<Input
id="iso-url"
placeholder="https://releases.example.org/linux-24.04-amd64.iso"
value={url}
onChange={(e) => setUrl(e.target.value)}
className="flex-1"
/>
<Button
type="button"
variant="outline"
onClick={handleDetectFilename}
disabled={!url.trim() || resolveFilename.isPending}
title="Определить имя файла по ссылке"
>
{resolveFilename.isPending
? <Loader2 className="h-4 w-4 animate-spin" />
: <Wand2 className="h-4 w-4" />}
</Button>
</div>
</div>
<div>
<Label htmlFor="iso-filename">Имя файла в хранилище</Label>
<Input
id="iso-filename"
placeholder={filenameFromUrl(url) || 'linux-24.04-amd64.iso'}
value={filename}
onChange={(e) => setFilename(e.target.value)}
/>
<p className="mt-1 text-xs text-muted-foreground">
Proxmox принимает только .iso и .img — иначе расширение будет добавлено автоматически.
Кнопка со звёздочкой рядом с URL определяет настоящее имя файла (по Content-Disposition
или итоговой ссылке после редиректов), если оно не видно из самого URL.
</p>
</div>
</TabsContent>
<TabsContent value="local" className="mt-4 space-y-3">
<input
ref={fileInputRef}
type="file"
accept=".iso,.img"
className="hidden"
onChange={(e) => pickFile(e.target.files?.[0])}
/>
</div>
<div>
<Label htmlFor="iso-filename">Имя файла в хранилище</Label>
<Input
id="iso-filename"
placeholder={filenameFromUrl(url) || 'linux-24.04-amd64.iso'}
value={filename}
onChange={(e) => setFilename(e.target.value)}
/>
<p className="mt-1 text-xs text-muted-foreground">
Proxmox принимает только .iso и .img — иначе расширение будет добавлено автоматически.
{!selectedFile ? (
<div
onClick={() => fileInputRef.current?.click()}
onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
onDragLeave={() => setIsDragging(false)}
onDrop={(e) => {
e.preventDefault();
setIsDragging(false);
pickFile(e.dataTransfer.files?.[0]);
}}
className={cn(
'flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-8 text-center transition-colors',
isDragging ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/50',
)}
>
<Upload className="h-8 w-8 text-muted-foreground" />
<p className="text-sm font-medium">Перетащите ISO-файл сюда</p>
<p className="text-xs text-muted-foreground">или нажмите, чтобы выбрать (.iso, .img)</p>
</div>
) : (
<div className="flex items-center justify-between rounded-lg border p-3">
<div className="min-w-0">
<p className="truncate text-sm font-medium">{selectedFile.name}</p>
<p className="text-xs text-muted-foreground">{fmtFileSize(selectedFile.size)}</p>
</div>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => setSelectedFile(null)}
title="Убрать файл"
>
<X className="h-4 w-4" />
</Button>
</div>
)}
<p className="text-xs text-muted-foreground">
Имя файла в хранилище назначается автоматически — из имени выбранного файла.
</p>
</div>
</>
</TabsContent>
</Tabs>
)}
<div>
@@ -209,8 +354,12 @@ export default function DownloadIsoDialog({ open, onClose, serverId, node, sourc
<DialogFooter>
<Button variant="outline" onClick={onClose}>Отмена</Button>
<Button onClick={submit} disabled={submitDisabled}>
{download.isPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
Скачать
{isPending
? <Loader2 className="mr-2 h-4 w-4 animate-spin" />
: mode === 'local' && !fromMirror
? <Upload className="mr-2 h-4 w-4" />
: <Download className="mr-2 h-4 w-4" />}
{mode === 'local' && !fromMirror ? 'Загрузить' : 'Скачать'}
</Button>
</DialogFooter>
</DialogContent>

View File

@@ -99,6 +99,50 @@ export function useDownloadImage(serverId: number) {
});
}
export interface ImageUploadRequest {
node: string;
storage: string;
content: 'iso' | 'vztmpl';
file: File;
filename?: string;
checksum?: string;
checksum_algorithm?: string;
}
// Загрузка локального файла (drag&drop) на ноду: multipart, без JSON.
export function useUploadImageFile(serverId: number) {
const qc = useQueryClient();
return useMutation({
mutationFn: (data: ImageUploadRequest) => {
const form = new FormData();
form.append('node', data.node);
form.append('storage', data.storage);
form.append('content', data.content);
if (data.filename) form.append('filename', data.filename);
if (data.checksum) form.append('checksum', data.checksum);
if (data.checksum_algorithm) form.append('checksum_algorithm', data.checksum_algorithm);
form.append('file', data.file);
return apiClient.postForm<{ task_id: number; status: string; name: string }>(
`/proxmox/api/${serverId}/images/upload`,
form,
);
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['all-tasks'] });
},
});
}
// Определить реальное имя файла по URL (Content-Disposition / хвост после редиректов).
export function useResolveFilename() {
return useMutation({
mutationFn: (url: string) =>
apiClient.get<{ filename: string }>(
`/proxmox/api/images/resolve-filename?url=${encodeURIComponent(url)}`,
),
});
}
// ── Custom mirrors (admin) ───────────────────────────────────────────────────
export function useImageMirrors(enabled = true) {

View File

@@ -128,6 +128,31 @@ class ApiClient {
headers,
});
return this.handleResponse<T>(res, path);
}
// multipart/form-data: без Content-Type (браузер сам проставит boundary) и
// без JSON.stringify тела — для загрузки файлов (напр. локальный ISO).
async postForm<T>(path: string, formData: FormData): Promise<T> {
const headers: Record<string, string> = {};
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
const wsId = getActiveWorkspaceId();
if (wsId) {
headers['X-Active-Workspace'] = String(wsId);
}
const res = await fetch(`${API_BASE}${path}`, {
method: 'POST',
headers,
body: formData,
});
return this.handleResponse<T>(res, path);
}
private async handleResponse<T>(res: Response, path: string): Promise<T> {
if (res.status === 401) {
// 401 от самого логина — это «неверный логин/пароль»: отдаём ошибку в
// форму, а не перезагружаем страницу (иначе сообщение теряется).

View File

@@ -11,7 +11,7 @@ export interface DeployTask {
node: string | null;
error_message: string | null;
created_at: number;
kind?: 'deploy' | 'vm_iso' | 'reinstall' | 'clone' | 'change_password' | 'image_download' | 'image_template' | 'migrate' | 'remote_migrate';
kind?: 'deploy' | 'vm_iso' | 'reinstall' | 'clone' | 'change_password' | 'image_download' | 'image_upload' | 'image_template' | 'migrate' | 'remote_migrate';
server_id?: number | null;
}