Angularjs如何上传多部分表单数据和文件?

时间:2014-06-27 02:58:02

标签: javascript forms angularjs post multipartform-data

我是angular.js的初学者,但我对基础知识有很好的把握。

我要做的是将文件和一些表单数据上传为多部分表单数据。我读到这不是角度的功能,但是第三方库可以完成这项工作。我已经通过git克隆了angular-file-upload,但是我仍然无法发布简单的表单和文件。

有人可以提供一个例子,html和js如何做到这一点?

4 个答案:

答案 0 :(得分:21)

这非常必须只是该项目演示页面的副本,并显示在表单提交上传单个文件并上传进度。

(function (angular) {
'use strict';

angular.module('uploadModule', [])
    .controller('uploadCtrl', [
        '$scope',
        '$upload',
        function ($scope, $upload) {
            $scope.model = {};
            $scope.selectedFile = [];
            $scope.uploadProgress = 0;

            $scope.uploadFile = function () {
                var file = $scope.selectedFile[0];
                $scope.upload = $upload.upload({
                    url: 'api/upload',
                    method: 'POST',
                    data: angular.toJson($scope.model),
                    file: file
                }).progress(function (evt) {
                    $scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
                }).success(function (data) {
                    //do something
                });
            };

            $scope.onFileSelect = function ($files) {
                $scope.uploadProgress = 0;
                $scope.selectedFile = $files;
            };
        }
    ])
    .directive('progressBar', [
        function () {
            return {
                link: function ($scope, el, attrs) {
                    $scope.$watch(attrs.progressBar, function (newValue) {
                        el.css('width', newValue.toString() + '%');
                    });
                }
            };
        }
    ]);
 }(angular));

HTML

<form ng-submit="uploadFile()">
   <div class="row">
         <div class="col-md-12">
                  <input type="text" ng-model="model.fileDescription" />
                  <input type="number" ng-model="model.rating" />
                  <input type="checkbox" ng-model="model.isAGoodFile" />
                  <input type="file" ng-file-select="onFileSelect($files)">
                  <div class="progress" style="margin-top: 20px;">
                    <div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
                      <span ng-bind="uploadProgress"></span>
                      <span>%</span>
                    </div>
                  </div>

                  <button button type="submit" class="btn btn-default btn-lg">
                    <i class="fa fa-cloud-upload"></i>
                    &nbsp;
                    <span>Upload File</span>
                  </button>
                </div>
              </div>
            </form>

编辑:添加了将模型传递到文件帖子中的服务器。

输入元素中的表单数据将在帖子的data属性中发送,并可作为普通表单值使用。

答案 1 :(得分:20)

首先

  1. 您不需要对结构进行任何特殊更改。我的意思是:html输入标签。
  2. <input accept="image/*" name="file" ng-value="fileToUpload"
           value="{{fileToUpload}}" file-model="fileToUpload"
           set-file-data="fileToUpload = value;" 
           type="file" id="my_file" />

    1.2创建自己的指令,

    .directive("fileModel",function() {
    	return {
    		restrict: 'EA',
    		scope: {
    			setFileData: "&"
    		},
    		link: function(scope, ele, attrs) {
    			ele.on('change', function() {
    				scope.$apply(function() {
    					var val = ele[0].files[0];
    					scope.setFileData({ value: val });
    				});
    			});
    		}
    	}
    })

    1. 在带有$ httpProvider的模块中,使用multipart / form-data添加依赖项(Accept,Content-Type等)。 (建议是,接受json格式的回复) 例如:
    2.   

      $ httpProvider.defaults.headers.post ['Accept'] ='application / json,text / javascript';       $ httpProvider.defaults.headers.post ['Content-Type'] ='multipart / form-data;字符集= UTF-8' ;

      1. 然后在控制器中创建单独的函数来处理表单提交调用。 比如以下代码:

      2. 在服务函数句柄“responseType”中故意使用,以便服务器不应抛出“byteerror”。

      3. transformRequest,修改附加标识的请求格式。

      4. withCredentials:false,用于HTTP身份验证信息。

      5. in controller:
        
          // code this accordingly, so that your file object 
          // will be picked up in service call below.
          fileUpload.uploadFileToUrl(file); 
        
        
        in service:
        
          .service('fileUpload', ['$http', 'ajaxService',
            function($http, ajaxService) {
        
              this.uploadFileToUrl = function(data) {
                var data = {}; //file object 
        
                var fd = new FormData();
                fd.append('file', data.file);
        
                $http.post("endpoint server path to whom sending file", fd, {
                    withCredentials: false,
                    headers: {
                      'Content-Type': undefined
                    },
                    transformRequest: angular.identity,
                    params: {
                      fd
                    },
                    responseType: "arraybuffer"
                  })
                  .then(function(response) {
                    var data = response.data;
                    var status = response.status;
                    console.log(data);
        
                    if (status == 200 || status == 202) //do whatever in success
                    else // handle error in  else if needed 
                  })
                  .catch(function(error) {
                    console.log(error.status);
        
                    // handle else calls
                  });
              }
            }
          }])
        <script src="//unpkg.com/angular/angular.js"></script>

答案 2 :(得分:2)

直接发送文件效率更高。

Content-Type: multipart/form-data的{​​{3}}会增加额外33%的开销。如果服务器支持它,则更有效地直接发送文件:

直接从https://developer.xamarin.com/recipes/ios/standard_controls/image_view/animate_an_imageview/

执行多个$http.post请求
$scope.upload = function(url, fileList) {
    var config = {
      headers: { 'Content-Type': undefined },
      transformResponse: angular.identity
    };
    var promises = fileList.map(function(file) {
      return $http.post(url, file, config);
    });
    return $q.all(promises);
};

发送带有base64 encoding的POST时,设置'Content-Type': undefined非常重要。然后,FileList会检测File object并自动设置内容类型。

&#34; select-ng-files&#34;的工作演示适用于ng-model XHR send method

的指令

默认情况下,<input type=file>元素不会与File object一起使用。它需要1

&#13;
&#13;
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);
      })
    }
  }
});
&#13;
<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="fileList" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileList">
      {{file.name}}
    </div>
  </body>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以查看此方法,以完全发送图像和表格数据

<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
                    <label for="image_name">Image Name:</label>
                    <input type="text"   placeholder="Image name" ng-model="fileName" class="form-control" required>
                    <br>

                    <br>
                    <input id="file_src" type="file"   accept="image/jpeg" file-input="files"   >
                    <br>
                        {{file_name}}
            <img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
                    <hr>
                      <button class="btn btn-info" ng-click="uploadFile()">Upload</button>
                        <br>

                       <div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
              <strong> {{response_msg}} </strong>
            </div>
                            <div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
                    </div>

Angular JS代码

    var app = angular.module("myApp", []);
 app.directive("fileInput", function($parse){
      return{
           link: function($scope, element, attrs){
                element.on("change", function(event){
                     var files = event.target.files;


                     $parse(attrs.fileInput).assign($scope, element[0].files);
                     $scope.$apply();
                });
           }
      }
 });
 app.controller("myCtrl", function($scope, $http){
      $scope.IsVisible = false;
      $scope.uploadFile = function(){
           var form_data = new FormData();
           angular.forEach($scope.files, function(file){
                form_data.append('file', file); //form file
                                form_data.append('file_Name',$scope.fileName); //form text data
           });
           $http.post('upload.php', form_data,
           {
                //'file_Name':$scope.file_name;
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined,'Process-Data': false}
           }).success(function(response){
             $scope.IsVisible = $scope.IsVisible = true;
                      $scope.response_msg=response;
               // alert(response);
               // $scope.select();
           });
      }

 });