Upload multiple files through UI

This commit is contained in:
Igor Katson 2024-09-13 10:52:39 +01:00
parent 7a807f39e0
commit e1dcb2602b
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5

View file

@ -1,17 +1,40 @@
import { RefObject, useRef, useState } from "react"; import { RefObject, useContext, useRef, useState } from "react";
import { UploadButton } from "./UploadButton"; import { UploadButton } from "./UploadButton";
import { CgFileAdd } from "react-icons/cg"; import { CgFileAdd } from "react-icons/cg";
import { APIContext } from "../../context";
import { useTorrentStore } from "../../stores/torrentStore";
export const FileInput = ({ className }: { className?: string }) => { export const FileInput = ({ className }: { className?: string }) => {
const inputRef = useRef<HTMLInputElement>() as RefObject<HTMLInputElement>; const inputRef = useRef<HTMLInputElement>() as RefObject<HTMLInputElement>;
const [file, setFile] = useState<File | null>(null); const [file, setFile] = useState<File | null>(null);
const API = useContext(APIContext);
const refreshTorrents = useTorrentStore((state) => state.refreshTorrents);
const onFileChange = async () => { const onFileChange = async () => {
if (!inputRef?.current?.files) { if (!inputRef?.current?.files) {
return; return;
} }
const file = inputRef.current.files[0]; if (inputRef.current.files.length == 1) {
setFile(file); const file = inputRef.current.files[0];
setFile(file);
} else {
const files = inputRef.current.files;
for (let i = 0; i < inputRef.current.files.length; i++) {
const file = inputRef.current.files[i];
API.uploadTorrent(file, { overwrite: true }).then(
() => {
console.log("uploaded file successfully");
refreshTorrents();
},
(err) => {
console.error("error uploading file", err);
}
);
}
reset();
}
}; };
const reset = () => { const reset = () => {
@ -34,6 +57,7 @@ export const FileInput = ({ className }: { className?: string }) => {
<input <input
type="file" type="file"
ref={inputRef} ref={inputRef}
multiple={true}
accept=".torrent" accept=".torrent"
onChange={onFileChange} onChange={onFileChange}
hidden hidden