AngularJS文件上传,上传的图片是空白的吗?

时间:2016-11-18 10:37:12

标签: angularjs parse-platform

我使用angular将文件上传到parse.com rest api。

我按照本教程AngularJS Upload tutorialspoint和REST上传文档REST Upload

然后我修改我的代码。这是我的代码。

//below code inside RegisterController
    $scope.upload = function () {

            //upload file
            var file = $scope.myFile;

         console.log('file is ' );
         console.dir(file);
         console.log(file.name);

         var uploadUrl = "http://128.199.249.233:1337/parse/files/"+file.name; //added file.name
         fileUpload.uploadFileToUrl(file, uploadUrl);
            //end upload file

    }
//above code inside RegisterController

//below code outside any controller
rentalkika.directive('fileModel', ['$parse', function ($parse) {
   return {
      restrict: 'A',
      link: function(scope, element, attrs) {
         var model = $parse(attrs.fileModel);
         var modelSetter = model.assign;

         element.bind('change', function(){
            scope.$apply(function(){
               modelSetter(scope, element[0].files[0]);
            });
         });
      }
   };
}]);

rentalkika.service('fileUpload', ['$http', function ($http) {
   this.uploadFileToUrl = function(file, uploadUrl){
      var fd = new FormData();
      fd.append('file', file);

      $http.post(uploadUrl, fd, {
         transformRequest: angular.identity,
         headers: {
            'X-Parse-Application-Id': 'secret',  //added this
            'Content-Type': undefined
            }
      })

      .success(function(response){
        console.log(response);
      })

      .error(function(){
      });
   }
}]);
//above code outside any controller

这是我的HTML

<form ng-controller="RegisterController">
<label>Upload file</label>
                     <input type="file" name="ktp" file-model="myFile">                      

                <label class="checkbox">
                    <input type="checkbox">Get hot offers via e-mail
                </label>
                <input type="submit" value="Sign up" class="btn btn-primary">
                <input type="button" value="Upload" ng-click="upload()" class="btn btn-primary">
                </form>

成功上传以201 created状态代码显示的文件,我收到成功回复,包括姓名和图片网址。

图片看起来像blank image

我的代码遗漏或错误了吗?

1 个答案:

答案 0 :(得分:1)

这是因为您的图像二进制数据未发送。 然后我使用这个https://github.com/danialfarid/ng-file-upload和一点点配置标题。

它有效。