douzhou7656 2019-06-05 09:37
浏览 87
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • dqd3690 2019-06-05 09:47
    关注

    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"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘