使用React JS&处理多张图片拉拉韦尔 [英] Handling multiple image upload with React JS & Laravel

查看:85
本文介绍了使用React JS&处理多张图片拉拉韦尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to upload multiple images to the database by using axios in reactjs to send the data from client-side to server-side and handle the image upload with laravel in the server-side. My problem is that whenever i try to handle multiple images at the server-side, it doesn't work.

这是我的代码.

客户端(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:

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);
        }
    }

HandleSubmitChange:

HandleSubmitChange:

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()循环并仅上载一张图像,它将成功保存该图像.如何利用循环保存多张图片?

I expect all uploaded images to be saved to the database. Instead, it throws an error: Invalid argument supplied for foreach(). Therefore, if i remove, the foreach() loop and upload only one image, it saves the image successfully. How can I make use of the loop to save multiple images?

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

UPDATE
This question has been answered in the comments below by @DelenaMalan. I updated the code in this question so that others searching for answers related to this problem can use the code to solve their problem.

推荐答案

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

In your frontend side you could use formData.append('file[]', image_file) to add your imagefiles to the file array in the form data, for example:

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

这篇关于使用React JS&处理多张图片拉拉韦尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆