2015-01-12 2 views
3

Gmail에서와 같이 '첨부'버튼을 클릭하면 찾아보기 창이 열리고 사용자 선택시 http 요청이 표시됩니다. 서버로 보냈습니다.파일 업로드시 앵글 업로드 파일 (기본 구현)

  1. 내가 원하지 않는 파일을 전송 버튼을 제출

    <form action="/upload" method="post" enctype="multipart/form-data"> 
             <input type="file" name="data" /> 
             <input type="submit">do it</input> 
    </form> 
    

    이것은 몇 가지 이유에 대한 좋은되지 않습니다 :

    오늘은 클라이언트에서 다음 코드를 사용하고 있습니다 서버에 사용자가 파일을 선택할 때 파일을 선택하면 해당 파일이 실행되기를 원합니다.

  2. 양식 기본 동작 동작은 내가 (같은 세부 HTTP POST 요청의 구현 (기본 각도 코드가 아닌 외부 라이브러리)을 찾고 있어요

다른 페이지로 사용자를 보낼 수 있습니다 enctype="multipart/form-data" 및 파일 세부 정보) 양식을 사용하지 않아도됩니다. 나도 몰라

답변

0

는 당신에 대해 여부를 이야기 이것을 native,하지만 난 내 프로젝트에서 이것을 사용

$scope.form = null; 
$scope.uploaded = []; 

$scope.upload = function(){ 
    var data = new FormData(document.forms.namedItem('form')); // form name 
    $http.post('/upload', data, {        // change with your endpoint 
    transformRequest: angular.identity, 
    headers: {'Content-Type': undefined} 
    }) 
    .success(function(res){ 
    $scope.uploaded.push(res); 
    $scope.form = null; 
    }); 
}; 

$scope.$watch('form', function(){ 
    $scope.upload(); 
}); 

HTML * :

<div ng-repeat="n in uploaded"> 
    {{n.filename}} 
</div> 

<form name="form"> 
    <input type="file" name="data" ng-model="form" /> 
</form> 

* 귀하의 입력 파일 이름을 숨기기 귀하의 CSS와 Gmail의 같은 ​​업로드를 만들 수 있습니다. 서버가 파일 이름이나 여기에 필요한 것을 반환했는지 확인하십시오. 서버가 "filename"키를 사용하여 파일 이름을 반환했다고 가정합니다. 위의 $ scope.uploaded를보십시오.

서버 쪽을 확인하십시오. filemultipart/form-data으로 보내고 data은 이름으로 사용하십시오. 이것은 사용자가 이미지/파일을 추가 할 때마다 실행되며, 서버 측에서 이런 종류의 것을 처리하는 것에주의하십시오. 평소처럼 submit 버튼을 사용하는 것이 좋습니다.

+0

사실 내가 파일을 선택할 때 처리하는 코드를 얻을 수있을 것입니다. –

+0

올바르게 실행되지 않는이 코드를 사용하고 있습니다. <입력 유형 = "파일"name = "데이터"onchange = "angle.element (this) .scope(). upload()"/> –

+0

Wait I 내 대답을 편집했습니다. –

0

여기 내 프로젝트에서 사용한 코드가 도움이 될 것입니다.

HTML :

<form role="form" name="myForm" ng-submit="submitCuisine()" novalidate> 
      <div class="form-group"> 
       <label for="description">Image</label> 
       <input type="file" file-input="files" name="file"/> 
      </div> 
      <button class="btn btn-primary" type="submit"> Submit</button> 
     </form> 

JS :

$scope.submitCuisine=function(){ 

     var fd=new FormData(); 
     angular.forEach($scope.files,function(file){ 
      fd.append('file',file); 
     }) 
     $http.post('admin/managecuisineAdd',fd,{ 
      transformRequest:angular.identity, 
      headers:{'Content-type':undefined} 
     }).success(function(data){ 
      $scope.message="Successfully" 
     }); 

} 

지침 :

myApp.directive("fileInput",['$parse',function($parse){ 
    return{ 
     restrict:'A', 
     link:function(scope,ele,attrs){ 
      ele.bind('change',function(){ 
       $parse(attrs.fileInput). 
       assign(scope,ele[0].files) 
       scope.$apply() 
      }); 
     } 
    } 
}]); 
관련 문제