I am having problems with formData to submit a pdf file
const [file,setFile] = useState()
const [isFilePicked, setIsFilePicked] = useState(false);
having an input type file
<input accept=".pdf" type="file" onChange={uploadFile}/>
and then the onChange function
const uploadImage = async (e) =>{
console.log(e.target.files[0])
setFile(e.target.files[0])
e.target.files[0] && setIsFilePicked(true);
}
At the end when I want to submit I got "FormData{}"
const post = async () => {
const formData = new FormData();
formData.append('File',file);
console.log(formData)
}
why am I getting this???
The FormData interface doesn't store the appended key value pairs directly into itself so logging the FormData itself won't output anything. Don't worry, the files are "stored" in the FormData nonetheless. To get the console.log() to log the files for you, you have to get the files out of the FormData first. One way is to get the iterator of FormData and then transforming it into object. Example:
Object.fromEntries(formData.entries()) // will result in { "File": <your file> }
so in case of your code snippet you can do as follows:
const post = async () => {
const formData = new FormData();
formData.append('File',file);
console.log(Object.fromEntries(formData.entries()))
}