File Upload using AngularJS

前端 未结 29 2421
野趣味
野趣味 2020-11-21 07:24

Here is my HTML form:

29条回答
  •  别那么骄傲
    2020-11-21 08:17

    Working Example using Simple Directive (ng-file-model):

    .directive("ngFileModel", [function () {
      return {
          $scope: {
              ngFileModel: "="
          },
          link: function ($scope:any, element, attributes) {
              element.bind("change", function (changeEvent:any) {
                  var reader = new FileReader();
                  reader.onload = function (loadEvent) {
                      $scope.$apply(function () {
                          $scope.ngFileModel = {
                              lastModified: changeEvent.target.files[0].lastModified,
                              lastModifiedDate: changeEvent.target.files[0].lastModifiedDate,
                              name: changeEvent.target.files[0].name,
                              size: changeEvent.target.files[0].size,
                              type: changeEvent.target.files[0].type,
                              data: changeEvent.target.files[0]
                          };
                      });
                  }
                  reader.readAsDataURL(changeEvent.target.files[0]);
              });
          }
      }
    }])
    

    and use FormData to upload file in your function.

    var formData = new FormData();
     formData.append("document", $scope.ngFileModel.data)
     formData.append("user_id", $scope.userId)
    

    all credits go for https://github.com/mistralworks/ng-file-model

    I have faced a small probelm you can check it here: https://github.com/mistralworks/ng-file-model/issues/7

    Finally,here's a forked repo: https://github.com/okasha93/ng-file-model/blob/patch-1/ng-file-model.js

提交回复
热议问题