programing

AngularJS: 멀티파트 형식으로 심플한 파일 업로드를 구현하려면 어떻게 해야 합니까?

newnotes 2023. 3. 1. 11:27
반응형

AngularJS: 멀티파트 형식으로 심플한 파일 업로드를 구현하려면 어떻게 해야 합니까?

Angular에서 간단한 멀티파트 폼 포스트를 하고 싶다.node.js 서버에 JS를 전송합니다.폼에는 한 부분에 JSON 오브젝트가 있고 다른 부분에 이미지가 포함되어 있어야 합니다.(현재 $resource를 가진 JSON 오브젝트만 게시하고 있습니다.)

입력 유형="file"로 시작해야겠다고 생각했는데 Angular가JS는 거기에 바인딩할 수 없습니다.

제가 찾을 수 있는 모든 예는 드래그 앤 드롭용 jQuery 플러그인을 랩하는 것입니다.하나의 파일을 간단하게 업로드하고 싶습니다.

Angular는 처음입니다.JS와 내 지시문을 쓰는 것이 전혀 편치 않다.

angularjs(v.1.0.6에서 테스트됨) 이외의 의존관계가 없는 실제 작동 솔루션

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs(1.0.6)는 "input-file" 태그의 ng-model을 지원하지 않으므로 선택한 모든 파일을 사용자로부터 전달하는 "native-way" 방식으로 수행해야 합니다.

컨트롤러

$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!... );

};

쿨한 부분은 정의되지 않은 content-type과 transformRequest: angular.identity입니다.이것에 의해, $http로 적절한 「content-type」을 선택해, 멀티파트 데이터를 처리할 때에 필요한 경계를 관리할 수 있게 됩니다.

simple/lightweight ng-file-upload 디렉티브를 사용할 수 있습니다.FileAPI flash shim을 탑재한 비HTML5 브라우저의 드래그 앤 드롭, 파일 진행률 및 파일 업로드를 지원합니다.

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'my/upload/url',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

파일을 직접 보내는 것이 더 효율적입니다.

base64 부호화Content-Type: multipart/form-data33%의 오버헤드가 추가됩니다.서버가 서포트하고 있는 경우는, 직접 파일을 송신하는 것이 효율적입니다.

$scope.upload = function(url, file) {
    var config = { headers: { 'Content-Type': undefined },
                   transformResponse: angular.identity
                 };
    return $http.post(url, file, config);
};

파일 오브젝트와 함께 POST를 송신할 때는,'Content-Type': undefined그러면 XHR 전송 메서드가 File 객체를 검출하고 콘텐츠 유형을 자동으로 설정합니다.

여러 파일을 보내려면 FileList에서 직접 여러 요청 수행을 참조하십시오.


입력 유형="file"로 시작해야겠다고 생각했는데 Angular가JS는 거기에 바인딩할 수 없습니다.

<input type=file>요소는 기본적으로는 ng-model 디렉티브에서는 동작하지 않습니다.커스텀 디렉티브가 필요합니다.

와 연동되는 "select-ng-files" 명령의 작업 데모ng-model1

angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileArray" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileArray">
      {{file.name}}
    </div>
  </body>


$http.post내용 유형 포함multipart/form-data

송신할 필요가 있는 경우multipart/form-data:

<form role="form" enctype="multipart/form-data" name="myForm">
    <input type="text"  ng-model="fdata.UserName">
    <input type="text"  ng-model="fdata.FirstName">
    <input type="file"  select-ng-files ng-model="filesArray" multiple>
    <button type="submit" ng-click="upload()">save</button>
</form>
$scope.upload = function() {
    var fd = new FormData();
    fd.append("data", angular.toJson($scope.fdata));
    for (i=0; i<$scope.filesArray.length; i++) {
        fd.append("file"+i, $scope.filesArray[i]);
    };

    var config = { headers: {'Content-Type': undefined},
                   transformRequest: angular.identity
                 }
    return $http.post(url, fd, config);
};

FormData API를 사용하여 POST를 전송할 때는 다음 설정을 하는 것이 중요합니다.'Content-Type': undefined그러면 XHR 송신방식이 검출됩니다.FormData오브젝트 및 콘텐츠유형 헤더를 적절한 경계를 가진 멀티파트/폼데이터로 자동 설정합니다.

방금 이 문제가 있었어요.몇 가지 방법이 있습니다.첫 번째는 새로운 브라우저가 다음을 지원한다는 것입니다.

var formData = new FormData();

링크를 클릭하면 최신 브라우저에 대한 지원이 제한되지만 그렇지 않으면 이 문제가 완전히 해결되는 방법에 대한 정보가 있는 블로그로 이동할 수 있습니다.

그렇지 않으면 대상 속성을 사용하여 iframe에 양식을 게시할 수 있습니다.양식을 게시할 때 표시 속성이 none으로 설정된 iframe으로 대상을 설정해야 합니다.대상은 iframe 이름입니다.(알려주세요)

이게 도움이 됐으면 좋겠다

를 통해 업로드 할 수 있습니다.$resourceactions다음과 같이 합니다.

$scope.uploadFile = function(files) {
    var fdata = new FormData();
    fdata.append("file", files[0]);

    $resource('api/post/:id', { id: "@id" }, {
        postWithFile: {
            method: "POST",
            data: fdata,
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        }
    }).postWithFile(fdata).$promise.then(function(response){
         //successful 
    },function(error){
        //error
    });
};

늦은 입력인 것은 알지만 간단한 업로드 지시문을 작성했습니다.금방 일을 할 수 있을 거야!

<input type="file" multiple ng-simple-upload web-api-url="/api/post"
       callback-fn="myCallback" />

ng-simple-upload는 웹 API를 사용한 예시와 함께 Github에 더 많이 업로드합니다.

AngularJs의 단순 업로더에 대한 간단한 지시문을 작성했습니다.

(정확한 jQuery 업로더 플러그인은 https://github.com/blueimp/jQuery-File-Upload) 입니다.

AngularJs를 사용한 심플 업로더(CORS 구현 포함)

(서버측이 PHP용이지만 노드 변경도 간단합니다)

언급URL : https://stackoverflow.com/questions/13963022/angularjs-how-to-implement-a-simple-file-upload-with-multipart-form

반응형