如何使用AngularJs在laravel中上传照片并存储到数据库?

时间:2017-05-23 08:12:12

标签: php angularjs mongodb laravel-5.2

这是我的Index.php文件,它描述了带有文件上传的新记录表单。这里也是我的控制器文件,模型文件和Angular模型文件以及javascript文件。请帮我把图像记录插入数据库(mongo db)。当我隐藏图像上传代码然后记录成功添加到数据库表,但是当我添加文件上传标签,然后它不工作。它showws" ReferenceError:响应未定义"错误

<div class="container">
    <div  ng-controller="employeesController">
        <div class="row">
            <div class="col-sm-6"><h2>Employees Database</h2></div>
            <div class="col-sm-6"><input type="text"  value="Search" ng-model="searchquery"  class="form-control"  placeholder="Search" style="margin-top: 20px;margin-bottom: 10px;"></div>
        </div>
        <!-- Table-to-load-the-data Part -->
        <table class="table table-striped table-bordered table-hover">
            <thead class="thead-inverse">
                <tr>
                    <th>ID</th>
                    <!--<th width="10%">Photo</th>-->
                    <th>Name</th>
                    <th>Email</th>
                    <th>Contact No</th>
                    <th>Position</th>
                    <th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button></th>
                </tr>
            </thead>
            <tbody>            
                <!--<tr ng-repeat="employee in filtered = (employees | filter:searchquery) | startFrom:(currentPage-1)*maxSize | limitTo:maxSize">-->
                <tr ng-repeat="employee in employees.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage)) | filter:searchquery">
                    <td>{{((currentPage-1) *itemsPerPage)+($index + 1)}}</td>
                    <!--<td><img ng-if="employee.photo" class="img-circle" src=".{{employee.photo}}" height="50" width="50"></td>-->
                    <td>{{ employee.name }}</td>
                    <td>{{ employee.email }}</td>
                    <td>{{ employee.contact_number }}</td>
                    <td>{{ employee.position }}</td>
                    <td>
                        <!--<button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee._id)"><i class="fa fa-edit text-info"></i></button>
                        <button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee._id)">Delete</button>-->
                        <a ng-click="toggle('edit', employee._id)" tooltip-placement="top" uib-tooltip="Edit {{ employee.name }}"><i class="fa fa-pencil text-info"></i></a>
                        <a ng-click="confirmDelete(employee._id)" tooltip-placement="top" uib-tooltip="Delete"><i class="fa fa-trash-o text-danger"></i></a>
                    </td>
                </tr>
            </tbody>
        </table>
        <!-- End of Table-to-load-the-data Part -->
        <div class="row">
            <div class="col-sm-6">View 
                <select ng-model="viewby" ng-change="setItemsPerPage(viewby)"><option>3</option><option>5</option><option>10</option></select> records at a time.
            </div>
            <div class="col-sm-6">
                <uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage"></uib-pagination>
            </div>
        </div>
        <!-- Modal (Pop up when detail button clicked) -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                        <h4 class="modal-title" id="myModalLabel">{{form_title}}</h4>
                    </div>
                    <div class="modal-body">
                        <form name="frmEmployees" class="form-horizontal" novalidate="" enctype="multipart/form-data">

                            <div class="form-group error">
                                <label for="inputEmail3" class="col-sm-3 control-label">Name</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
                                    ng-model="employee.name" ng-required="true">
                                    <span class="help-inline"
                                    ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Email</label>
                                <div class="col-sm-9">
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
                                    ng-model="employee.email" ng-required="true">
                                    <span class="help-inline"
                                    ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
                                    ng-model="employee.contact_number" ng-required="true">
                                <span class="help-inline"
                                    ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Position</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
                                    ng-model="employee.position" ng-required="true">
                                <span class="help-inline"
                                    ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Photo</label>
                                <div class="col-sm-9">
                                    <input ng-model="employee.image" type="file" class="form-control" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)" >
                                    <img ng-src="{{image_source}}" style="width:300px;">
                                </div>
                            </div>

                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>

AngularJS代码:

app.controller('employeesController', function($scope, $filter, $http, API_URL) {
    //retrieve employees listing from API
    $http.get(API_URL + "employees").then(successCallback, errorCallback);
    function successCallback(response){
        //success code      
        $scope.employees = response.data;
        $scope.viewby = '10';
        $scope.totalItems = response.data.length;
        //alert($scope.totalItems);
        $scope.currentPage = '1';
        $scope.itemsPerPage = $scope.viewby;
        $scope.maxSize = '10'; //Number of pager buttons to show
        $scope.setPage = function (pageNo) {
          $scope.currentPage = pageNo;
        };
        $scope.pageChanged = function() {
          console.log('Page changed to: ' + $scope.currentPage);
        };
        $scope.setItemsPerPage = function(num) {
          $scope.itemsPerPage = num;
          $scope.currentPage = 1; //reset to first page
        }

        $scope.noOfPages = Math.ceil($scope.employees.length/$scope.maxSize);
        //alert($scope.noOfPages);
        $scope.filter = function() {
            $timeout(function() { 
                $scope.noOfPages = Math.ceil($scope.filtered.length/$scope.maxSize);
            }, 10);
        };
    }
    function errorCallback(error){
        //error code
    }




    //show modal form
    $scope.toggle = function(modalstate, id) {
        $scope.modalstate = modalstate;

        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Employee";
                break;
            case 'edit':
                $scope.form_title = "Employee Detail";
                $scope.id = id;
                $http.get(API_URL + 'employees/' + id).then(successCallback, errorCallback);
                        function successCallback(response){
                            //success code
                            console.log(response);
                            $scope.employee = response.data;
                        }
                        function errorCallback(error){
                            //error code
                        }
                break;
            default:
                break;
        }
        console.log(id);
        $('#myModal').modal('show');
    }
    //save new record / update existing record
    $scope.save = function(modalstate, id) {
        $scope.frmEmployees.image = $scope.files[0];
        var url = API_URL + "employees";
        //append employee id to the URL if the form is in edit mode
        if (modalstate === 'edit'){
            url += "/" + id;
            //alert(url);
        }
        $http({
            method: 'POST',
            url: url,
            transformRequest: function (data) {
                  var formData = new FormData();
                  formData.append("image", $scope.employee.image);  
                  //alert(formData);
                  return formData;  
              },  
            data: $.param($scope.employee),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })
        .then(success, error);
            function success(response){
                console.log(response);
                location.reload();
            }
            function error(error){
                console.log(response);
                alert('This is embarassing. An error has occured. Please check the log for details');
            }
    }


    $scope.uploadedFile = function(element) {
            $scope.currentFile = element.files[0];
            var reader = new FileReader();

            reader.onload = function(event) {
              $scope.image_source = event.target.result

              $scope.$apply(function($scope) {
                $scope.files = element.files;
              });
            }
                    reader.readAsDataURL(element.files[0]);
          }


    //delete record
    $scope.confirmDelete = function(id) {
        var isConfirmDelete = confirm('Are you sure you want this record?');
        if (isConfirmDelete) {
            $http({
                method: 'DELETE',
                url: API_URL + 'employees/' + id
            })
                    .then(success, error);
            function success(response){
                console.log(response);
                location.reload();

            }
            function error(error){
                console.log(response);
                alert('This is embarassing. An error has occured. Please check the log for details');
            }
        } else {
            return false;
        }
    }
});
/*app.filter('startFrom', function() {
    return function(input, start) {
      start = +start; //parse to int
      return input.slice(start);
    };
});*/



var app = angular.module('employeeRecords', ['ui.bootstrap']).constant('API_URL', 'http://localhost/blog/public/');

PHP代码:

<?php

namespace App\Http\Controllers;

use App\Employee;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class Employees extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index($id = null) {
        if ($id == null) {
            return Employee::orderBy('id', 'asc')->get();
        } else {
            return $this->show($id);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */


    public function store(Request $request) {
        $employee = new Employee;

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');

        $employee->photo =$request->file('photo');
        $filename=$employee->getClientOriginaName();
        storage::put('uploads/'.$filename,file_get_contents($request->file('photo')->getRealPath()));
        $employee->image=$filename;

        $employee->photo = 'uploads/'. $request->input('photo');



        $employee->save();

        return 'Employee record successfully created with id ' . $employee->id;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        return Employee::find($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id) {
        $employee = Employee::find($id);

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');
        $employee->save();

        return "Sucess updating user #" . $employee->id;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */

     public function destroy(Request $request)
      {
        $employee = Employee::find($request->id);
        $employee->delete();

            return "Employee record successfully deleted #" . $request->id;
        }

} 


<?php

namespace App;

//use Illuminate\Database\Eloquent\Model;
//use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Model as Eloquent;


class Employee extends Eloquent
{
   public $collection = 'employees';
   public $fillable = ['id', 'name', 'email','contact_number','position','photo'];
}




<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('index');
});

Route::get('/employees/{id?}', 'Employees@index');
Route::post('/employees', 'Employees@store');
Route::post('/employees/{id}', 'Employees@update');
Route::delete('/employees/{id}', 'Employees@destroy');

2 个答案:

答案 0 :(得分:0)

您可能需要查看此laravel's Documentation以了解如何将上传的图像存储到目录中,然后使用query buildereloquent将文件名插入数据库。

答案 1 :(得分:0)

&#39; ReferenceError:&#39;部分建议您遇到JavaScript错误。第二部分,关于回应&#39;未定义,表示未定义响应属性。实际上,这是.NET中臭名昭着的NullReferenceException的JavaScript版本;)。

由于JS代码中唯一可以实际访问“响应”的地方。属性是两个成功的回调,我会从那里开始。另一方面,在您的错误回调中,您还尝试使用console.log&#39; response&#39;,这不是一个有效的变量(您只指定&#39;错误&#39;)。

请尝试修复错误回调,如果这不起作用,请尝试评论那些您尝试使用“回复”的JS代码段。变量一个接一个。鉴于相当小的代码,我认为调试不应该那么难;)。