How to upload image with angularjs

对着背影说爱祢 提交于 2019-12-02 09:44:12

问题


I am trying to upload image with angularjs.

HTML:

<input type="file" id="picture" name="picture"/>
<button class="btn btn-primary" ng-click="AddNew()" type="submit">Save</button>

Controller.js

$scope.AddNew=function(){
    console.log(picture.files.item(0));
    $scope.myobject.picture=picture[0];

    $http({
        url: 'http://localhost/mypro/resource',
        method: "POST",
        data: {'resource' : $scope.myobject },
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    })
    .then(function(response) {
        // success

    }, 
    function(response) { // optional
        // failed
    });
};

Laravel 5.2:

routes.php

Route::resource('resource','ResourceController');

Controller:

public function store(Request $request){

    Log::info('request: '.print_r(Input::all(),true));
    Log::info('request: '.print_r($request,true));
    return array('success' => true);
}

Just getting empty array here. And in console I am getting 500 (Internal Server Error).

Please guide me what I am doing wrong.

Thank you.


回答1:


Ok,

I have found the solution by searching deep in SO.

Here is solution:

var profile_pic=picture.files.item(0);
var jsonData=$scope.myobject;
$http({
    url: 'http://localhost/mypro/resource',
    method: "POST",
    headers: {'Content-Type': undefined },
    transformRequest: function (data) {
        var formData = new FormData();
        formData.append("model", angular.toJson($scope.myobject));
        formData.append("profile_pic", picture.files.item(0));

        return formData;
    },
    data: {'myobject' : jsonData,'profile_pic':profile_pic},

Thanx SO :)



来源:https://stackoverflow.com/questions/36406260/how-to-upload-image-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!