I want that users should be able to upload any image.
The code below gives me the URL but using that URL in the src of image doesn't work.
There is another method where you send the file as an object to the backend. That doesn't work either. Since I have a user object with other key value pairs like "name", "date" etc adding other whole object to key makes things way too complicated.
--
import React, { useState} from "react";
import { Link } from "react-router-dom";
import Axios from 'axios';
export default function PostJournalEntry(){
/* Hooks */
const [selectedFile, setSelectedFile] = useState();
const [file, setFile] = useState();
const [name, setName] = useState();
const [title, setTitle] = useState();
const [journalEntry, setJournalEntry] = useState();
const [date, setDate] = useState();
/* End of Hooks */
/* Click Handlers */
const handleName = (e)=>{
setName("Anonynamus")
}
const handleTitle = (e)=>{
setTitle(e.target.value)
}
const handleJournalEntry = (e)=>{
setJournalEntry(e.target.value)
}
const handleDate = () =>{
const dateTime = new Date().toLocaleString('en-GB')
setDate(dateTime)
}
const handleFile = (e)=>{
const fileObject = e.target.files[0]
const fileUrl = URL.createObjectURL(fileObject)
console.log("File URL", fileUrl)
setFile(fileUrl)
}
const dateTime = new Date().toLocaleString('en-GB')
const postData = () =>{
const dataToSend = {
name:"Anonymus",
title:title,
journalEntry:journalEntry,
date:dateTime,
file:file
}
console.log("DataToSend", dataToSend)
Axios.post("http://localhost:5000/post", dataToSend).then((response)=>{
alert("Journal Entry Submitted!")
console.log("Post Data", response.data)
})
.catch((error)=>{console.log(error)})
}
/* End of Click Handlers */
return(
<main className ="post__main">
<form onSubmit={(e)=>{e.preventDefault()}} className = "post__form">
<input onChange={handleFile} type = "file"/>
<input onChange={handleTitle} type = "text" placeholder= "Title"/>
<input onChange={handleJournalEntry}type = "text" placeholder = "Journal Entry"/>
<button onClick = {postData} className = "form__button">Submit Entry</button>
<img className="post__image" url={file}/>
</form>
<button onClick={handleFileUpload}>Upload Image</button>
<Link to = "/">Back to HomePage</Link>
</main>
)
}
Thank you in advance people!
CodePudding user response:
in your code , file submit to server is a string like "blob://xxxxxxxxxxx",
it's meaningless for server side,
right code:
const handleFile = (e)=>{
setFile(e.target.files[0])
}
const fileURL = React.useMemo(()=> file && URL.createObjectURL(file), file);
// ...
<img src={fileURL} />
and how to send file in axios it's another problem search