AngularJS Uploading An Image With ng-upload

前端 未结 4 1034
清酒与你
清酒与你 2020-12-02 08:31

I am trying to upload a file in AngularJS using ng-upload but I am running into issues. My html looks like this:

4条回答
  •  独厮守ぢ
    2020-12-02 09:06

    There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)

    html

    
    

    Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

    controller

    $scope.uploadFile = function(files) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);
    
        $http.post(uploadUrl, fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).success( ...all right!... ).error( ..damn!... );
    
    };
    

    The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

提交回复
热议问题