简体   繁体   English

React dropzone似乎没有将文件发送到我的PHP端点

[英]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. 我刚刚开始学习React,所以任何帮助将不胜感激。

I'm trying to write a small multiple image upload page with react-dropzone and Laravel as a backend. 我正在尝试用react-dropzone和Laravel作为后端编写一个小的多图像上传页面。

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. 图像正在通过laravel验证正确传递,还有if( $request->hasFile('myimages') ) { line,但是当它到达foreach循环时它找不到任何东西。 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. 我不确定这是一个laravel的东西或反应的东西,我猜测反应,因为我之前使用过这个PHP上传脚本。

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; 我的Laravel代码是;

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. 在此先感谢您的帮助。

Try to use data.append('myimages[]', file, file.name); 尝试使用data.append('myimages[]', file, file.name); instead data.append('myimages', file, file.name); 而不是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. 正如这里建议的那样使用formData()上传多个文件,因为它看起来像你的代码检测不是文件数组,而是单个文件。

Also, check if you send proper content-type header - should be "Content-Type: multipart/form-data" 另外,检查是否发送了正确的内容类型标题 - 应该是“Content-Type:multipart / form-data”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM