Skip to content

Instantly share code, notes, and snippets.

@codiini
Created August 1, 2022 19:41
Show Gist options
  • Save codiini/32b562a3057f631cbbd01e614cac1ea5 to your computer and use it in GitHub Desktop.
Save codiini/32b562a3057f631cbbd01e614cac1ea5 to your computer and use it in GitHub Desktop.
Restricing explicit content upload with Gatsby cloud functions
import React, { useState } from "react"
import * as styles from "../components/index.module.css"
const IndexPage = () => {
const [file, setFile] = useState()
const [uploadedImg, setUploadedImg] = useState()
const [moderatedImage, setModeratedImage] = useState()
const [isLoading, setIsLoading] = useState(false)
const [isError, setIsError] = useState(false)
const submitForm = async e => {
e.preventDefault()
const formData = new FormData()
formData.append("file", file)
try {
const response = await fetch("/api/upload", {
method: "POST",
body: formData,
})
const image = await response.json()
setIsLoading(true)
//Here we'll store information about the uploaded image to our app's state
setUploadedImg(image)
setFile(null)
} catch (err) {
console.log(err)
}
}
const handleFileInputChange = e => {
setFile(e.target.files[0])
}
return (
<div className={styles.wrapper}>
<h1 className={styles.title}>
Content Moderation with Gatsby Functions & Cloudinary
</h1>
<div className={styles.container}>
<form
onSubmit={submitForm}
action="/api/upload"
encType="multipart/form-data"
method="POST"
>
<div className={styles.formContainer}>
{file && <p>{file.name}</p>}
<label className={styles.inputLabel} htmlFor="file">
Choose a file to upload
</label>
<input
onChange={handleFileInputChange}
type="file"
name="file"
id="file"
/>
<button type="submit">Upload Photo</button>
</div>
</form>
<div className={styles.imageWrapper}>
<div className={styles.messages}>
{!uploadedImg && <p>Moderated Image goes in here</p>}
{isError && (
<p className={styles.error}>
Image has been flagged for inappropriate content
</p>
)}
{isLoading && (
<p className={styles.upload}>
Image has been uploaded and is pending moderation...
</p>
)}
{moderatedImage && (
<img src={moderatedImage.url} alt="moderated content" />
)}
</div>
</div>
</div>
</div>
)
}
export default IndexPage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment