Почему ошибка при загрузке файла через Dropzone js?

214
21 апреля 2022, 03:40

Контроллер

public function dropzoneform()
{   
    $products = Product::all();
    return view('products.add_product_image', compact("products"));
}
public function storeData(Request $request)
{
    try {
        $product = new ProductImage;
        $product->product_id = $request->product;
        $product->save();
        $user_id = $product->id; // this give us the last inserted record id
    }
    catch (\Exception $e) {
        return response()->json(['status'=>'exception', 'msg'=>$e->getMessage()]);
    }
    return response()->json(['status'=>"success", 'user_id'=>$user_id]);
}
// We are submitting are image along with userid and with the help of user id we are updateing our record
public function storeImage(Request $request)
{
    if($request->file('file')){
        $img = $request->file('file');
        //here we are geeting userid alogn with an image
        $userid = $request->userid;
        $imageName = strtotime(now()).rand(11111,99999).'.'.$img->getClientOriginalExtension();
        $user_image = new ProductImage();
        $original_name = $img->getClientOriginalName();
        $user_image->image = $imageName;
        if(!is_dir(public_path() . '/uploads/images/')){
            mkdir(public_path() . '/uploads/images/', 0777, true);
        }
    $request->file('file')->move(public_path() . '/uploads/images/', $imageName);
    // we are updating our image column with the help of user id
    $user_image->where('id', $userid)->update(['image'=>$imageName]);
    return response()->json(['status'=>"success",'imgdata'=>$original_name,'userid'=>$userid]);
    }
}

web.php

Route::get('/dropzoneform', 'ProductController@dropzoneform');
Route::post('/storedata', 'ProductController@storeData')->name('form.data');
Route::post('/storeimgae', 'ProductController@storeImage');

JS

$(document).ready(function(){
    Dropzone.autoDiscover = false;
    // Dropzone.options.demoform = false;   
    let token = $('meta[name="csrf-token"]').attr('content');
    $(function() {
        var myDropzone = new Dropzone("div#dropzoneDragArea", { 
            paramName: "file",
            url: "{{ url('/storeimgae') }}",
            previewsContainer: 'div.dropzone-previews',
            addRemoveLinks: true,
            autoProcessQueue: false,
            uploadMultiple: false,
            parallelUploads: 1,
            maxFiles: 1,
            params: {
                _token: token
            },
             // The setting up of the dropzone
            init: function() {
                var myDropzone = this;
                //form submission code goes here
                $("form[name='demoform']").submit(function(event) {
                    //Make sure that the form isn't actully being sent.
                    event.preventDefault();
    
                    URL = $("#demoform").attr('action');
                    formData = $('#demoform').serialize();
                    $.ajax({
                        type: 'POST',
                        url: URL,
                        data: formData,
                        success: function(result){
                            if(result.status == "success"){
                                // fetch the useid 
                                var userid = result.user_id;
                                $("#userid").val(userid); // inseting userid     into     hidden input field
                                //process the queue
                                myDropzone.processQueue();
                            }else{
                                console.log("error");
                            }
                        }
                    });
                });
                //Gets triggered when we submit the image.
                this.on('sending', function(file, xhr, formData){
                    //fetch the user id from hidden input field and send that     userid     with our image
                    let userid = document.getElementById('userid').value;
                    formData.append('userid', userid);
                });
            
                this.on("success", function (file, response) {
                    //reset the form
                    $('#demoform')[0].reset();
                    //reset dropzone
                    $('.dropzone-previews').empty();
                });
                this.on("queuecomplete", function () {
            
                });
            
                // Listen to the sendingmultiple event. In this case, it's     the     sendingmultiple event instead
                // of the sending event because uploadMultiple is set to     true.
                this.on("sendingmultiple", function() {
                    // Gets triggered when the form is actually being sent.
                    // Hide the success button or the complete form.
                });
            
                this.on("successmultiple", function(files, response) {
                    // Gets triggered when the files have successfully been     sent.
                    // Redirect user or notify of success.
                });
            
                this.on("errormultiple", function(files, response) {
                    // Gets triggered when there was an error sending the     files.
                    // Maybe show form again, and notify user of error
                });
            }
        });
    });
});

HTML

<!-- form starts -->
        <form action="{{ route('form.data') }}" name="demoform" id="demoform" method="POST" class="dropzone" enctype="multipart/form-data">
            @csrf 
                <div class="form-group">
                    <input type="hidden" class="userid" name="userid" id="userid" value="">
                </div>
                <div class="form-group">
                    <label for="product">Продукт</label><span class="require-star">*</span>
                    <select name="product" id="product" class="form-control">
                        @foreach($products as $product)
                            <option value="{{ $product->id }}">{{ $product->title }}</option>
                        @endforeach
                    </select>
                    <!-- <span class="require-field">{ { $errors->first('product_id') }}</span> -->
                </div>
                <div class="form-group">
                    <div id="dropzoneDragArea" class="dz-default dz-message dropzoneDragArea">
                        <span>Upload file</span>
                    </div>
                    <div class="dropzone-previews"></div>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-md btn-primary">create</button>
                </div>
            </form>
    <!-- form end -->
READ ALSO
Как из одного файла записать в другой?

Как из одного файла записать в другой?

Как из одного файла записать в другой и нужно отредактировать определенные столбцы

220
Как добавить магазин в woocommerce?

Как добавить магазин в woocommerce?

так получилось, что я удалил страницу магазина в woocommerce с целью поменять страницу магазина, на свою страницу магазина, уже сверстаннуюУдалил...

210
убрать знак ? из урл

убрать знак ? из урл

У меня есть такие ссылки http://mishka-gamesxyz/game/?wrecked и http://mishka-games

86