programing

angularjs 용 파일 업 로더 통합

nasanasas 2020. 11. 18. 09:14
반응형

angularjs 용 파일 업 로더 통합


AngularJS와 잘 통합 된 (지시문) 좋은 파일 업 로더가 있습니까?

스타일링하기 쉽고 HTML5 드래그 앤 드롭 등을 지원하는 것을 찾고 있습니다.

누군가는 아마 기존 업 로더를 사용하고 AngularJS에 통합하기 쉽다고 말할 것입니다. 즉, 그것이 쉽다면 누군가 이미 그것을 했어야했습니다.


나는 실제로 내 업 로더를 한 번 롤링했지만 이미 만든 JQuery를 좋아하지 않았기 때문입니다. 불행히도 그것은 독점적이며 인터넷에 게시 할 수는 없지만 ... Angular의 모든 JQuery 플러그인을 사용하는 방법을 보여줄 수 있습니다.

누군가는 아마도 기존 업 로더를 사용하고 AngularJS에 통합하기 쉽다고 말할 것입니다. 즉, 그것이 쉽다면 누군가 이미 그것을 했어야했습니다.

div를 선택하고 호출하여 작동하는 jQuery 플러그인이 있다고 가정 해 보겠습니다 pluginUploadCall().

app.directive('myJqueryPluginUploader', function() {
   return {
      restrict: 'A',
      link: function(scope, elem, attr, ctrl) {
          // elem is a jQuery lite object
          // or a jQuery object if jQuery is present.
          // so call whatever plugins you have.
          elem.pluginUploadCall();
      }
   };
});

그리고 이것이 사용되는 방법입니다.

<div my-jquery-plugin-uploader></div>

Angular는 실제로 jQuery와 잘 통합되므로 jQuery에서 작동하는 모든 플러그인은 Angular에서 매우 쉽게 작동합니다. Angular 앱을 테스트 가능한 상태로 유지할 수 있도록 Dependency Injection을 유지하려는 경우 유일한 까다로운 점이 있습니다. JQuery는 DI를 잘하지 못하므로 몇 가지 문제를 해결해야 할 수도 있습니다.

직접 굴리고 싶다면 다음과 같이했다고 말할 수 있습니다.

app.directive('customUploader', function(){
    return {
       restrict: 'E',
       scope: {},
       template: '<div class="custom-uploader-container">Drop Files Here<input type="file" class="custom-uploader-input"/><button ng-click="upload()" ng-disabled="notReady">Upload</button></div>',
       controller: function($scope, $customUploaderService) {
          $scope.notReady = true;
          $scope.upload = function() {
             //scope.files is set in the linking function below.
             $customUploaderService.beginUpload($scope.files);
          };
          $customUploaderService.onUploadProgress = function(progress) {
             //do something here.
          };
          $customUploaderService.onComplete = function(result) {
             // do something here.
          };
       },
       link: function(scope, elem, attr, ctrl) {
          fileInput = elem.find('input[type="file"]');
          fileInput.bind('change', function(e) {               
               scope.notReady = e.target.files.length > 0;
               scope.files = [];
               for(var i = 0; i < e.target.files.length; i++) {
                   //set files in the scope
                   var file = e.target.files[i];
                   scope.files.push({ name: file.name, type: file.type, size: file.size });
               }
          });
       }
});

파일을 게시하고 서버에서 진행 상황을 확인 하는 데 사용 $customUploaderService하는 사용자 지정 서비스는 어디에 있습니까 ?Module.factory()$http

그것이 모호하다는 것을 알고 있으며, 그게 제가 제공 할 수있는 전부라고 죄송하지만 도움이되기를 바랍니다.

편집 : 드래그 앤 드롭 파일 업로드는 CSS, BTW ... Chrome 및 FF의 트릭입니다. 포함하는 div에 넣은 다음 다음과 같이하십시오.

<div class="uploadContainer">Drop Files Here<input type="file"/></div>
div.uploadContainer {
   position: relative;
   width: 600px;
   height: 100px;
}

div.uploadContainer input[type=file] {
   visibility: hidden;
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
}

... 이제 해당 div에 놓은 모든 항목은 파일 업로드에 실제로 삭제되며 div를 원하는 모양으로 만들 수 있습니다.


AngularJS.ngUpload 를 사용해 볼 수 있습니다 .

파일 업로드를 위해 보이지 않는 iFrame을 사용하는 HTML5 무료 솔루션입니다. HTML5에 의존하지 않기 때문에 모든 브라우저에서 작동합니다!

샘플 코드 :

<form action='/server/upload/handler' ng-upload="callbackFunction">
   <!-- other form inputs goes here -->
   <input type="file" name="anyEasyName" />
   <input type="submit" class="upload-submit" value="Submit" />
</form>
<div>{{uploadReport}}</div>

클릭 이벤트를 지원하는 모든 html 요소는 ngUpload 지시문으로 표시된 양식을 제출하는 데 사용할 수 있습니다. 이러한 요소는 위의 input [type = submit]의 경우와 같이 upload-submit css 클래스 로 표시되어야합니다 .

아래 예에서는 스타일이 지정된 div를 사용하여 양식을 제출합니다.

<form action='/server/upload/handler' ng-upload="callbackFunction">
   <!-- other form inputs goes here -->
   <input type="file" name="anyEasyName" />
   <div style="cursor: pointer; padding: 5px" class="upload-submit">Submit</div>
</form>
<div>{{uploadReport}}</div>

You can make your /server/upload/handler spit a valid url, so that {{uploadReport}} can be used to set the src of an <img> tag, like so:

<img ng-src={{uploadReport}} />

and see the uploaded image appear immediately!

The ngController for the above examples is:

var UploadCtrl = function ($scope) {
     $scope.callbackFunction = function(contentOfInvisibleFrame) {
         $scope.uploadReport = contentOfInvisibleFrame;
     }
}

The ngUpload directive can be registered with your AngularJS application module viz:

var mainApp = angular.module('MainApp', ["ngUpload", ...]);

and added to your document as:

<html ng-app="MainApp">

</html>

AngularJS.ngUpload works in the context of a ngController; and such you can have as many uploaders as possible in a single ngController. For example:

<form action='/server/upload/handler' ng-upload="callbackFunction1">
   <!-- other form inputs goes here -->
   <input type="file" name="anyEasyName" />
   <input type="submit" class="upload-submit" value="Submit" />
</form>
Server response: {{uploadReport1}}

<form action='/server/upload/handler' ng-upload="callbackFunction2">
   <!-- other form inputs goes here -->
   <input type="file" name="anotherEasyName" />
   <input type="submit" class="upload-submit" value="Submit" />
</form>
Server response: {{uploadReport2}}

to be served by:

var UploadCtrl = function ($scope) {
     $scope.callbackFunction1 = function(contentOfInvisibleFrame) {
         $scope.uploadReport1 = contentOfInvisibleFrame;
     }

     $scope.callbackFunction2 = function(contentOfInvisibleFrame) {
         $scope.uploadReport2 = contentOfInvisibleFrame;
     }
}

A NodeJS-based upload handler demo of this directive can be found at http://ng-upload.eu01.aws.af.cm.

An ASP.Net MVC and NodeJS sample codes can be found on the project website at github.com/twilson63/ngUpload/tree/master/examples

Hope this helps.


I have put together a simple/light angular directive with polyfill for browsers not supporting HTML5 FormData here:

https://github.com/danialfarid/ng-file-upload

You can send other model object along with the file to the server. Here is the demo page:

http://angular-file-upload.appspot.com/

<script src="angular.min.js"></script>
<script src="ng-file-upload.js"></script>

<div ng-controller="MyCtrl">
  <input type="text" ng-model="myModelObj">
  <input type="file" ngf-select ng-model="files" >
</div>

controller:

Upload.upload({
    url: 'my/upload/url',
    data: {myObj: $scope.myModelObj},
    file: $scope.files
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

If you want to handle multiple files, try this

jQuery File Upload Angularjs wrap from the original author (blueimp)

I think it is the most powerful uploader so far.


I recently wrote a directive that supports native multiple file uploads.

Example usage:

<lvl-file-upload
    auto-upload='false'
    choose-file-button-text='Choose files'
    upload-file-button-text='Upload files'
    upload-url='http://localhost:3000/files'
    max-files='10'
    max-file-size-mb='5'
    get-additional-data='getData(files)'
    on-done='done(files, data)'
    on-progress='progress(percentDone)'
    on-error='error(files, type, msg)'/>

You can find the code on github, and the documentation on my blog

참고URL : https://stackoverflow.com/questions/12979712/file-uploader-integration-for-angularjs

반응형