Search code examples
javascriptphpreactjslaravelreact-dropzone

React dropzone doesn't seem to be sending files to my PHP endpoint


Good Evening,

I am having a little issue with some code im writing. Im just starting out learning React so any help would be greatly appreciated.

I'm trying to write a small multiple image upload page with react-dropzone and Laravel as a backend.

When i hit the submit button, the email address is being passed through fine, but something is happening with the images. the images are being passed correctly through the laravel validation and also the if( $request->hasFile('myimages') ) { line, but when it gets to the foreach loop it doesnt find anything. Im not sure if this is a laravel thing or a react thing, im guessing react as I have used this php upload script before.

My react code is as follows;

import React, { Component } from "react";
import Dropzone from 'react-dropzone';
import axios from 'axios';

class SendSomething extends Component {

    constructor(props) {
        super(props);

        this.onDrop = (files) => {
            this.setState({files})
        };

        this.state = {
            files: [],
            email: ''
        };
    }

    onChangeHandler = e => {
        this.setState(
            { email: e.target.value }
        )
    };

    onClickHandler = () => {
        const data = new FormData();

        data.append('emailaddress', this.state.email);
        this.state.files.forEach(file => {
            data.append('myimages', file, file.name);
        });

        axios.post("/api/endpoint", data, {
        })
            .then(res => {
                alert(res.data.message);

                this.setState({
                    email: '',
                    files: []
                });
            })
    };

    render() {

        const files = this.state.files.map(file => (
            <li key={file.name}>
                {file.name} - {file.size} bytes
            </li>
        ));

        return (

            <div>

                <form>

                    <div className="form-group">
                        <label htmlFor="exampleInputEmail1">Email</label>
                        <input type="email" name="email" value={this.state.email} onChange={this.onChangeHandler} className="form-control" id="exampleInputEmail1" placeholder="Enter email" />
                    </div>

                    <div>
                        <Dropzone
                            onDrop={this.onDrop}
                            accept="image/png, image/gif, image/jpeg"
                            minSize={0}
                            maxSize={5242880}
                            multiple
                        >
                            {({getRootProps, getInputProps}) => (
                                <section className="container">
                                    <div {...getRootProps({className: 'dropzone'})}>
                                        <input {...getInputProps()} />
                                        <p>Click here or drop a file to upload!</p>
                                    </div>
                                    <aside>
                                        <ul>{files}</ul>
                                    </aside>
                                </section>
                            )}
                        </Dropzone>
                    </div>

                    <button type="button" onClick={this.onClickHandler} className="btn btn-primary">Submit</button>
                </form>

            </div>

        );
    }
}

export default SendSomething;

and my Laravel code is;

public function store(Request $request)
{
    request()->validate([
        'emailaddress' => 'required',
        'myimages' => 'required',
        'myimages.*' => 'image|mimes:jpeg,jpg,gif,png'
    ]);

    if( $request->hasFile('myimages') ) {

        foreach($request->file('myimages') as $image) {

            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('images'), $imageName);

            $data[]['emailaddress'] = $request->input('emailaddress');
            $data[]['imagename'] = $imageName;
        }

    }

    $success = ImageUpload::insert($data);

    return $this->sendResponse($success, 'Uploaded successfully.');

}

Thanks for any help in advance.


Solution

  • Try to use data.append('myimages[]', file, file.name); instead data.append('myimages', file, file.name); as suggested here Uploading multiple files using formData() because it looks like your code detect not array of files, but single file.

    Also, check if you send proper content-type header - should be "Content-Type: multipart/form-data"