【问题标题】:Handling multiple image upload with React JS & Laravel使用 React JS 和 Laravel 处理多张图片上传
【发布时间】:2019-08-30 23:10:29
【问题描述】:

我想通过在 reactjs 中使用 axios 将数据从客户端发送到服务器端并在服务器端使用 laravel 处理图像上传,将多个图像上传到数据库。我的问题是,每当我尝试在服务器端处理多个图像时,它都不起作用。

这是我的代码。

客户端(ReactJS)

构造器:

constructor(props){
        super(props);
        this.state = {
            id: "upload-photo",
            imageArray: [],
            body: '',
            posts: [],
            // image: []
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleBodyChange = this.handleBodyChange.bind(this);
    }

HanleFileChange:

handleFileChange(e){
        if (e.target.files) {
            const files = Array.from(e.target.files);

            const promises = files.map(file => {
                return (new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.addEventListener('load', (ev) => {
                        resolve(ev.target.result);
                    });
                    reader.addEventListener('error', reject);
                    reader.readAsDataURL(file);
                }))
            });

            Promise.all(promises).then(images => {
                this.setState({
                    imageArray: images
                })
            }, error => { console.error(error); });
        }
        if (this.props.onChange !== undefined) {
            this.props.onChange(e);
        }
    }

处理提交更改:

handleSubmit(e) {
        e.preventDefault();
        // this.postData();
        const formData = new FormData();
        this.state.imageArray.forEach((image_file) => {
             formData.append('file[]', image_file);
        });
        formData.append('body', this.state.body);
        for (let pair of formData.entries()) {
            console.log(pair[0]+ ', ' + pair[1]);
        }
        axios.post('/posts', formData)
            .then(response => {
            this.setState({
                posts: [response.data]
            })
        });
        this.setState({
            body: ''
        });
    }

服务器端(LARAVEL)

public function create(Request $request, Post $post) {
        $data = [];
        if ($request->get('file')) {
            foreach ($request->get('file') as $file) {
                $name = time() . '.' . explode('/', explode(':', substr($file, 0, strpos($file, ';')))[1])[1];
                \Image::make($file)->save(public_path('images/') . $name);
                array_push($data, $name);
            }
        }
        $image = json_encode($data);
        // create post
        $createdPost = $request->user()->posts()->create([
            'body' => $request->body,
            'image' => $image
        ]);
        // return the response
        return response()->json($post->with('user')->find($createdPost->id));
    }

我希望所有上传的图像都保存到数据库中。相反,它会引发错误:Invalid argument supplied for foreach()。因此,如果我删除 foreach() 循环并仅上传一张图像,它会成功保存图像。如何利用循环保存多张图片?

更新
@DelenaMalan 在下面的 cmets 中回答了这个问题。我更新了此问题中的代码,以便其他搜索与此问题相关的答案的人可以使用该代码来解决他们的问题。

【问题讨论】:

  • 快速猜测:JSON.stringify 文件数组,然后将其附加到 formData
  • 在前端试试这个:this.state.imageArray.forEach((image_file) => { formData.append('file[]', image_file); });
  • 感谢@DelenaMalan。这就像一个魅力:)
  • 很高兴听到@IsraelObanijesu 我会把它作为答案发布。

标签: javascript php reactjs laravel laravel-5.8


【解决方案1】:

在您的前端,您可以使用formData.append('file[]', image_file) 将您的图像文件添加到表单数据中的file 数组中,例如:

this.state.imageArray.forEach((image_file) => {
    formData.append('file[]', image_file);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2020-09-27
    • 2015-04-23
    • 2020-10-07
    • 1970-01-01
    • 2019-09-05
    • 2018-04-28
    相关资源
    最近更新 更多