From b2160bab04abea6d86d0f6d2fb73f7aae69840b1 Mon Sep 17 00:00:00 2001 From: dm1sh Date: Thu, 15 Jul 2021 12:26:53 +0500 Subject: [PATCH] Added file uploading form component and file validation --- src/App/index.tsx | 3 +- src/UploadForm/UploadForm.module.css | 0 src/UploadForm/index.tsx | 57 ++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 src/UploadForm/UploadForm.module.css create mode 100644 src/UploadForm/index.tsx diff --git a/src/App/index.tsx b/src/App/index.tsx index b965b23..66e42af 100644 --- a/src/App/index.tsx +++ b/src/App/index.tsx @@ -1,10 +1,11 @@ import React from "react"; import Bookshelf from "../Bookshelf"; +import { UploadForm } from "../UploadForm"; import styles from "./App.module.css"; export const App = () => (
- +
); diff --git a/src/UploadForm/UploadForm.module.css b/src/UploadForm/UploadForm.module.css new file mode 100644 index 0000000..e69de29 diff --git a/src/UploadForm/index.tsx b/src/UploadForm/index.tsx new file mode 100644 index 0000000..5e26933 --- /dev/null +++ b/src/UploadForm/index.tsx @@ -0,0 +1,57 @@ +import React, { useState } from "react"; + +const validState = (input: HTMLInputElement) => { + const file = input.files?.[0]; + + if (!file) throw new Error("Book file is required. Please, attach one"); + + if (!file.name.match(/\.(fb2|epub)/)) + throw new Error( + "Wrong file type. Only FB2 and Epub files are supported. \ + If you are trying to upload fb2.zip, please, uncopress it first." + ); + + if (file.size > 100 * 1024 * 1024) + throw new Error( + "File size is too big. Sorry, but parser is served on a rather cheap hosting, \ + so application can't handle such big files." + ); + + return true; +}; + +export const UploadForm = () => { + const [error, setError] = useState(""); + + const handleFileChange = (e: React.ChangeEvent) => { + setError(""); + const fileInput = e.currentTarget; + + try { + validState(fileInput); + } catch (e) { + setError(e.message); + } + }; + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + }; + + return ( +
+
+ + +

{error}

+ +
+
+ ); +};