javascript - formData.append() is not sending file to the server? - Stack Overflow

admin2025-04-19  0

I am writing some React.js that will upload multiple photos at a time. I am currently trying to send a batch of photos to the server but I cannot seem to get the files to append to the formData.

I call this function on the onChange event of the input field:

batchUpload(e) {
    e.preventDefault();

    let files = e.target.files;

    for (let i = 0; i < files.length; i++) {
        let file = files[i],
            reader = new FileReader();
        reader.onload = (e) => {
            let images = this.state.images.slice();

            if (file.type.match('image')) {
                images.push({file, previewURL: e.target.result});
                this.formData.append('files', file); //THIS IS NOT APPENDING THE FILE CORRECTLY
                this.setState({images});
            }
        };
        reader.readAsDataURL(file);
    }

    this.props.setFormWasEdited(true);
}

Then once the save button is pressed I run this function:

saveClick(goBack, peopleIdArray) {
    if (this.state.images.length > 0) {

        let formData = this.formData;
        formData.append('token',  Tokens.findOne().token);
        formData.append('action', 'insertPhotoBatch');
        formData.append('tags', peopleIdArray);
        formData.append('date', dateString());

        for (var pair of formData.entries()) {
            console.log(pair[0] + ', ' + JSON.stringify(pair[1]));
        }

        let xhr = new XMLHttpRequest();

        xhr.open('POST', Meteor.settings.public.api, true);
        xhr.onload = (e) => {
            if (xhr.status === 200) {
                // upload success
                console.log('XHR success');
            } else {
                console.log('An error occurred!');
            }
        };
        xhr.send(formData);

    } else {
        //signifies error
        return true;
    }
}

Everything seems to be fine until I append the files to the formData. What am I doing wrong?

I am writing some React.js that will upload multiple photos at a time. I am currently trying to send a batch of photos to the server but I cannot seem to get the files to append to the formData.

I call this function on the onChange event of the input field:

batchUpload(e) {
    e.preventDefault();

    let files = e.target.files;

    for (let i = 0; i < files.length; i++) {
        let file = files[i],
            reader = new FileReader();
        reader.onload = (e) => {
            let images = this.state.images.slice();

            if (file.type.match('image')) {
                images.push({file, previewURL: e.target.result});
                this.formData.append('files', file); //THIS IS NOT APPENDING THE FILE CORRECTLY
                this.setState({images});
            }
        };
        reader.readAsDataURL(file);
    }

    this.props.setFormWasEdited(true);
}

Then once the save button is pressed I run this function:

saveClick(goBack, peopleIdArray) {
    if (this.state.images.length > 0) {

        let formData = this.formData;
        formData.append('token',  Tokens.findOne().token);
        formData.append('action', 'insertPhotoBatch');
        formData.append('tags', peopleIdArray);
        formData.append('date', dateString());

        for (var pair of formData.entries()) {
            console.log(pair[0] + ', ' + JSON.stringify(pair[1]));
        }

        let xhr = new XMLHttpRequest();

        xhr.open('POST', Meteor.settings.public.api, true);
        xhr.onload = (e) => {
            if (xhr.status === 200) {
                // upload success
                console.log('XHR success');
            } else {
                console.log('An error occurred!');
            }
        };
        xhr.send(formData);

    } else {
        //signifies error
        return true;
    }
}

Everything seems to be fine until I append the files to the formData. What am I doing wrong?

Share Improve this question edited Nov 14, 2021 at 5:30 Nimantha 6,4966 gold badges31 silver badges76 bronze badges asked Aug 24, 2016 at 16:59 dpasie2dpasie2 931 gold badge1 silver badge11 bronze badges 3
  • What makes you think it isn't working? One immediate problem I can see is that this.formData.append('files', file) should be above/outside the reader.onload function. You don't need to wait for the reader to finish before you append the files to the formData. – idbehold Commented Aug 24, 2016 at 17:24
  • It could be that your server is expecting the key to be files[] instead of files. So try changing the line to this.formData.append('files[]', file) – idbehold Commented Aug 24, 2016 at 17:31
  • 1 @idbehold : Moving the append does not seem to change anything. I have also changed the key to files[], but that also seems to change nothing. The reason I think it isn't working is because formData.entries() includes all of the keys except for the file, and the PHP endpoint I am hitting does not receive any files. – dpasie2 Commented Aug 24, 2016 at 18:05
Add a ment  | 

3 Answers 3

Reset to default 1

If I'm not mistaken you problem is with this.formData.append('files', file); Running this line in a for loop will get you 1 field with all the file appended to each other resulting in an invalid file.

Instead you must file the file "array" syntax used informs like so:

this.formData.append('files[]', file);

This way you get the files on server side as $_FILES['files']['name'][0], $_FILES['files']['name'][1], ... and like wise for other properties of the files array.

I hope you have solved your issues already. I am still stuck not understanding why it would seem that my formData is not bringing anything to my server, but I did find an issue with your code.

When you use

JSON.stringify(pair[1])

the result looks like an empty array. If you instead try

pair[1].name 

you'd see that append actually did attach your file.

 const config = {
            headers: { 'content-type': 'multipart/form-data' }
        }
        const formData = new FormData();
    
        Object.keys(payload).forEach(item => {
            formData.append([item], payload[item])
        })

pass this formData to your API.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745022084a280440.html

最新回复(0)