Laravel 5.2仅在上传多个图像文件时返回1的数组

时间:2016-10-17 08:40:43

标签: php laravel-5.2

我无法在Laravel 5.2中从阵列中获取正确数量的图像,并且控制器只将其中一个图像复制到public / img文件夹而不是我选择的所有图像。以下是我的代码:

// js code
$(".start").on("click", function(e) {
    var formData    = new FormData(),
        sumMsg      = $( "#upload .summary-message" );

    $( files.files ).each(function( inx ) {
      formData.append('files', files.files[inx]);
      alert(files.files[inx].name);
    });

    // formData.append('files', fileUpload.files[0]);

    $.ajax({
        url: "{{ url('/files/upload') }}",
        type: "POST",
        data: formData,
        enctype: 'multipart/form-data',
        contentType: false,
        processData: false
    })
    .done(function(data) {
        // log data to the console so we can see
        console.log(data);

        // here we will handle errors and validation messages
        if ( data.success != true ) {
            sumMsg.removeClass( "success" );
            sumMsg.addClass( "error" );
            sumMsg.html( data.message );
        } else {
            sumMsg.removeClass( "error" );
            sumMsg.addClass( "success" );
            sumMsg.html( data.message );
        }
    })
    // using the fail promise callback
    .fail(function(data) {
        // show any errors
        // best to remove for production
        console.log(data);

        sumMsg.removeClass( "success" );
        sumMsg.addClass( "validation-summary error" );
        sumMsg.html( "Server Error: " + data.statusText + " processing your request, please contact Ticket 2 Africa or report a bug." );
    });
});

// form.blade.php
@if (count($errors) > 0)
    <div class="validation-summary">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
<br />

<div class="control-group">
    <div class="controls">
        <span class="fileinput-button">
            <label for="files">Upload image(s) : </label>
            <input type="file" id="files" name="files[]" multiple>
        </span>
        <p class="errors">{!!$errors->first('image')!!}</p>
        @if(Session::has('error'))
            <p class="errors">{!! Session::get('error') !!}</p>
        @endif
    </div>
</div>
<div id="success"> </div>
<button type="submit" class="start">Start upload</button>
<button type="reset" class="cancel">Cancel upload</button>
<button type="button" class="delete">Delete</button>
<input type="checkbox" class="toggle">

// FileUploadController Controller
public function upload(Request $request) {
    // getting all of the post data
    // $files = array('image' => Input::file('files'));

    $files = array("image" => Input::file("files"));
    // setting up rules
    $rules = array('image' => 'required|required|image|mimes:jpeg,png,jpg,gif,svg|max:1024',);      //mimes:jpeg,png and for max size max:1024
    // doing the validation, passing post data, rules and the messages
    $validator = Validator::make($files, $rules);
    if ($validator->fails()) {
        // send back to the page with the input data and errors
        return Redirect::to('upload')->withInput()->withErrors($validator);
    } else {
        // checking file is valid.
        if (Input::file('files')->isValid()) {
            $destinationPath = public_path('img');                  // upload path
            $extension = Input::file('files')->getClientOriginalExtension();                            // getting image extension

            foreach ($files as $file) {
                $fileName = rand(11111, 99999).'.'.$extension;                                            // renameing image
                $file->move($destinationPath, $fileName);                                                 // uploading file to given path
            }

            // sending back with message
            Session::flash('success', 'Upload successfully'); 
            return Redirect::to('auth/packagesandspecials');
        } else {
            // sending back with error message.
            Session::flash('error', 'uploaded file is not valid');
            return Redirect::to('auth/packagesandspecials');
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您的js代码出错:

$(".start").on("click", function(e) {
var formData    = new FormData(),
    sumMsg      = $( "#upload .summary-message" );

$( files.files ).each(function( inx ) {
  formData.append('files', files.files[inx]);//THIS IS THE MISTAKE
  formData.append('files[]',files.files[inx]);/*THIS SHOULD BE DONE LIKE THIS BECAUSE IN YOUR CODE ON EVERY LOOP KEY 'files' data is replaced it is not appending as an array */
  alert(files.files[inx].name);
});

答案 1 :(得分:0)

我设法将图片上传工作,但我确定它不是理想的解决方案。以下是我的代码:

// js code
$(".start").on("click", function(e) {
    var formData    = new FormData(),
        sumMsg      = $( "#upload .summary-message" );

    // TODO: This needs work, should use formData.append('files[]', files.files[inx]);
    $( files.files ).each(function( inx ) {
        formData.append('files', files.files[inx]);

        $.ajax({
            url: "{{ url('/files/upload') }}",
            type: "POST",
            data: formData,
            enctype: 'multipart/form-data',
            contentType: false,
            processData: false
        })
        .done(function(data) {
            // log data to the console so we can see
            console.log(data);

            // here we will handle errors and validation messages
            if ( data.success != true ) {
                sumMsg.removeClass( "success" );
                sumMsg.addClass( "error" );
                sumMsg.html( data.message );
            } else {
                sumMsg.removeClass( "error" );
                sumMsg.addClass( "success" );
                sumMsg.html( data.message );
            }
        })
        // using the fail promise callback
        .fail(function(data) {
            // show any errors
            // best to remove for production
            console.log(data);

            sumMsg.removeClass( "success" );
            sumMsg.addClass( "validation-summary error" );
            sumMsg.html( "Server Error: " + data.statusText + " processing your request, please contact Ticket 2 Africa or report a bug." );
        });
    });
});

// form.blade.php
@if (count($errors) > 0)
    <div class="validation-summary">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
<br />

<div class="control-group">
    <div class="controls">
        <span class="fileinput-button">
            <label for="files">Upload image(s) : </label>
            <input type="file" id="files" name="files[]" multiple>
        </span>
        <p class="errors">{!!$errors->first('image')!!}</p>
        @if(Session::has('error'))
            <p class="errors">{!! Session::get('error') !!}</p>
        @endif
    </div>
</div>
<div id="success"> </div>
<button type="submit" class="start">Start upload</button>
<button type="reset" class="cancel">Cancel upload</button>
<button type="button" class="delete">Delete</button>
<input type="checkbox" class="toggle">

// FileUploadController controller
public function upload(Request $request) {
    $files = array("image" => Input::file("files"));
    // setting up rules
    $rules = array('image' => 'required|required|image|mimes:jpeg,png,jpg,gif,svg|max:1024',);        //mimes:jpeg,png and for max size max:1024
    // doing the validation, passing post data, rules and the messages
    $validator = Validator::make($files, $rules);
    if ($validator->fails()) {
        // send back to the page with the input data and errors
        return Redirect::to('upload')->withInput()->withErrors($validator);
    } else {
        // checking file is valid.
        if (Input::file('files')->isValid()) {
            $destinationPath = public_path('img/packages and specials/holiday types');              // upload path
            $extension = Input::file('files')->getClientOriginalExtension();                        // getting image extension

            foreach ($files as $file) {
                $fileName = rand(11111, 99999).'.'.$extension;                                      // renameing image
                $file->move($destinationPath, $fileName);                                           // uploading file to given path
            }

            // sending back with message
            Session::flash('success', 'Upload successfully'); 
            return Redirect::to('auth/packagesandspecials');
        } else {
            // sending back with error message.
            Session::flash('error', 'uploaded file is not valid');
            return Redirect::to('auth/packagesandspecials');
        }
    }
}