1

I'm trying to upload a file using formik but the file object is always empty and I cannot quite figure it out. Here is a link to the codesandbox - https://codesandbox.io/s/formik-file-input-with-validation-forked-r5jqg?file=/src/App.js

I got this implementation from this issue filed on github - https://github.com/formium/formik/issues/926.

Your help would be greatly appreciated.

1 Answer 1

1

You were setting an object which was e.target.files[0] to a file which was initially undefined. you need to set e.taregt.files[0] to reader.readAsDataURL(file). not to your state object file too. you need to set name and size as that is what you need for validation schema and display. I've commented the supported formats from validation schema as for input type=file you can directly mention the accepted formats by accept key.

Here is my working modified sandbox.

Sign up to request clarification or add additional context in comments.

4 Comments

I notice that when I alert the formik values object, the file object is empty but upon console logging it, I do see the file object. My problem is that when I post the formik values object to the server, it shows up as an empty object inside req.body.
Did you checked my sandbox link ? it's working fine there.
I've updated my demo. now the file object is coming. Can you check is that what you wanted ?
Okay, as far as I can tell, the reason why the file was not properly getting posted to the server is that the payload was not of type FormData. To fix this, I added this - const formData = new FormData(); formData.append("photo", values.file);, in Formik's onSubmit handler and then passed formData as the payload to axios. Initially I thought, the file object being empty on alert was causing the issue but that is not the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.