0

My goal is to create field in formData which contains array of File objects

My code (with example of output in console):

const onChange = (e) => {
        const files = e.target.files // contains FileList itself
        console.log(files) // FileList {0: File, 1: File, length: 2}
        .....
        var _formData = new FormData();
        var filesArr = Array.from(files) // try to cast FileList to Array type
        console.log(filesArr) // (2) [File, File]
        formData.append("files", filesArr) 
        for (var value of _formData.entries()) {
                console.log(value[0], ',', value[1], ',', typeof (value[1]));
                // files , [object File],[object File] , string

                                }

The problem is that I receive object File with type string instead of needed array of files (objects). Are there any ways how can it be casted?

11
  • You should loop over your files array, and then call formData.append for each of the entries individually. Commented Aug 4, 2022 at 14:07
  • @CBroe do you mean that? If so, I've tried this, it doesn't work:( files.ForEach(element => { formData.append("files", element) }) Commented Aug 4, 2022 at 14:16
  • Where is the part where you actually send this to the server? Commented Aug 4, 2022 at 14:25
  • BACKEND.get('/count_word_in_documents_total', _formData) .then(response => { console.log(response) }) BACKEND is: export const BACKEND = axios.create({ baseURL: process.env.REACT_APP_BACKEND_BASE_URL, }) Commented Aug 4, 2022 at 14:29
  • You're expecting to do file uploads with a GET request ...? (Assuming the method nomen est omen here.) Commented Aug 4, 2022 at 14:30

1 Answer 1

1

According to MDN, If the field value is different than String or Blob it will be automatically converted to String. because this type of field is always a string.

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

5 Comments

If I clearly understood, there is no way to do this?
yes sir. may I know why you need to check the type of form field?
if you talk about checking in console output this is just for debugging. So sad, that there is no solution, but thank you anyway:(
if you liked my answer please upvote :).
unfortunately, I don't have enough reputation to vote, but I press this button :)

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.