1
votes

My vue component to upload file image like this :

<template>
    <section>
        <ul class="media-list">
            ...
        </ul>
    </section>
</template>

<script>
    export default {
        ...
        props: ['productId'],
        methods: {
            ...
            onFileChange(e, index) {
                let files = e.target.files,
                let formData = new FormData()
                formData.append('file', files[0])
                axios.post(window.App.baseUrl+'/admin/product/upload-image',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                ).then(function(){
                    console.log('SUCCESS!!')
                })
                .catch(function(){
                    console.log('FAILURE!!')
                });
            }
        }
    }
</script>

So it will call onFileChange method if user upload file image

My routes like this :

Route::prefix('admin')->group(function(){
    Route::prefix('product')->group(function(){
        Route::post('upload-image', 'Admin\ProductController@uploadImage')->name('admin.product.upload-image');
    });
});

My controller like this :

public function uploadImage(Request $request)
{
    echo '<pre>';print_r($request->all());echo '</pre>';die();
}

The code works. I success get file uploaded in the controller

But here I want to pass another paramater too. I want to pass parameter productId

I try change code axios like this :

...
axios.post(window.App.baseUrl+'/admin/product/upload-image',
{product_id: this.productId, formData}
...

It does not work. The result is empty

How can I solve this problem?

1

1 Answers

6
votes

Put product_id in formData.

let formData = new FormData();
formData.append('file', files[0]);
formData.append('product_id', this.productId);

axios.post(window.App.baseUrl+'/admin/product/upload-image', formData)
  .then(function(){
    console.log('SUCCESS!!')
  })
  .catch(function(){
    console.log('FAILURE!!')
  });