Skip to content

Commit

Permalink
Added size limit for uploading files
Browse files Browse the repository at this point in the history
- If the file size is above 10MB, display alert
  • Loading branch information
mbeps committed Feb 22, 2023
1 parent 4286dad commit e5b1eeb
Showing 1 changed file with 31 additions and 10 deletions.
41 changes: 31 additions & 10 deletions src/hooks/useSelectFile.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
import React, { useState } from "react";

/**
* Hook provides functionality to select a file.
* @returns selectedFile - the selected file
* @returns setSelectedFile - function to set the selected file
* @returns onSelectFile - function to select a file
*/
const useSelectFile = () => {
const [selectedFile, setSelectedFile] = useState<string>();

/**
* Allows user to select a file.
* The file size limit is 10MB.
* @param event (React.ChangeEvent<HTMLInputElement>) - event object
*/
const onSelectFile = (event: React.ChangeEvent<HTMLInputElement>) => {
const fileReader: FileReader = new FileReader();
// files in an array that can store multiple files if needed
if (event.target.files?.[0]) {
fileReader.readAsDataURL(event.target.files[0]); // passed to firebase storage
}

fileReader.onload = (readerEvent) => {
if (readerEvent.target?.result) {
setSelectedFile(readerEvent.target.result as string);
const file = event.target.files?.[0]; // get the first file
const maxImageSize = 10; // 10MB
if (file) {
// check if file exists
if (file.size > maxImageSize * 1024 * 1024) {
// check if file size is too large
alert(
`File size is too large. Maximum file size is ${maxImageSize}MB.`
); // alert user
return; // exit function
}
};
const fileReader: FileReader = new FileReader();
fileReader.readAsDataURL(file); // passed to firebase storage

fileReader.onload = (readerEvent) => {
if (readerEvent.target?.result) {
// check if fileReader has a result
setSelectedFile(readerEvent.target.result as string); // set the selected file
}
};
}
};
return {
selectedFile,
Expand Down

0 comments on commit e5b1eeb

Please sign in to comment.