Search code examples
reactjslaravelaxiosintervention

500 internal server error while upload multiple images via react and axios into laravel storage


I get 500 internal server error whenever I try to store image in laravel

this is my jsx:

<form onSubmit={this.handleSubmit} className={"dashboard-cards-form"} encType={"multipart/form-data"} >
      <div className={"dashboard-cards-title"}>Atvirutės</div>
      <input onChange={this.handleFileChange} type="file" className={"dashboard-cards-input"} name="dashboard-cards-input" id="dashboard-cards-input" multiple={true}/>
      <label className={"dashboard-cards-label"} htmlFor="dashboard-cards-input">Pasirink atvirutes</label>
      <input type={"submit"} value={"Įkelk"} className={"dashboard-cards-submit"}/>
</form>

this is my handleFileChange:

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

This is my handleSubmit:

async handleSubmit (e){
        e.preventDefault();
        var self = this;
        var cookie = new Cookie();
        const formData = new FormData();
        this.state.imageArray.forEach((image_file) => {
            formData.append('file[]', image_file);
        });

        axios({
            method: 'post',
            url: '/api/admin/uploadCards',
            data: formData,
            headers: {
                'Authorization' : 'Bearer ' + cookie.get('access_token'),
                "Content-type": "multipart/form-data"
            }
        })
            .then(function (response) {
                console.log(response.data);
                self.setState({
                 imageArray: []
                });
            })
            .catch(error => {
               console.log(error)
            })
    };

This is my laravel controller:

public function uploadCards(Request $request) {
        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('cards/') . $name);
            }
            return response(['upload' => 'success']);
        }
        return response(['upload' => 'error no files ']);
    }

If I comment out Image::make($file)->save(public_path('cards/') . $name); I get the response, I also tried using laravel Storage::put() but it's always the same 500 error

I can get base64 code, I am able to get the name, but the storage is killing me for 3 days now, I've surfed stackoverflow and tried everything, however I can't find what I am missing


Solution

  • Just making an answer so you can close your question

    First thing to do:
    Always look at the log.

    As you mentioned, it was logged

    local.ERROR: Can't write image data to path (C:\laravel\sveikinimai2019\public\cards/1564144716.jpeg) {"userId":5,"exception":"[object]

    So we know the problem is when saving the image. This kind of message is, in general, related to permissions or missing directory.

    Since you wanted in public/assets/cards/ but provided public/cards/ by changing Image::make($file)->save(public_path('cards/') . $name); to Image::make($file)->save(public_path('assets/cards/') . $name); will solve your issue