Javascript react safe image in database

82 views Asked by At

I have a problem with saving pictures in the database. I want to do a post Method, where i can safe a file in a directory and save the picture link in the database.

Here is my Code:

`const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
})`

` const [base64Image, setBase64Image] = useState("")
   const [imagePath, setImagePath] = useState("")
    const fileInput = useRef(null)`



`const onFileInputChange = async (e) => {
        const file = fileInput.current.files[0]
        if (!file) return
        const base64 = await toBase64(file)
        setBase64Image(base64)}`

`    const handleSubmitImage = async (e) => {
        e.preventDefault()

        if (!base64Image) return

        const response = await fetch("/public", {
            method: "POST",
            headers: {
                "content-type": "application/json"
            },
            body: JSON.stringify(base64Image)
        })
        const data = await response.json()
        setImagePath(data.filePath)
    }`

Post:

    `const handleSubmit = async (e) => {
        e.preventDefault()
        setIsLoading(true)
        setErrors(defaultModel)

        const result = validateModel(post)

        if (!result.isValid) {
            setErrors(result.errors)
            setIsLoading(false)
            return
        }

        if (post.id) {
            await updatePost(post, session.accessToken)
            alert("Post updated!")
            router.push(`/posts/${post.id}`)
        } else {
            const newPost = await createPost(post, session.accessToken)
            alert("Post created!")
            router.push(`/posts/${newPost.id}`)
        }
        setIsLoading(false)
    }
`
`                <fieldset onSubmit={handleSubmitImage} className={styles.form}>
                    <p>Image:</p>

                    <input value={post.image}
                           type="file"
                           accept=".png,.jpg"
                           ref={fileInput}
                           onChange={onFileInputChange}
                    />

                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    {base64Image && <img src={base64Image} style={{width: "1000px", height: "1000px"}} alt={""}/>}


                    {imagePath && <p>
                        <Link href={`http://localhost:3000${imagePath}`}
                              passHref><a>http://localhost:3000{imagePath}</a></Link>
                    </p>
                    }
                </fieldset>`

Right now i can connect to the Explorer and pick an Image. I can also display the image. If i press on create, it doesnt work properly with saving the image in the database.

0

There are 0 answers