Angularjs如何上传多部分表单数据和文件? [英] Angularjs how to upload multipart form data and a file?

查看:1134
本文介绍了Angularjs如何上传多部分表单数据和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者angular.js但我有一个有基本把握好。

我所希望做的是上传文件,某种形式的数据作为多部分的表单数据。我看,这是没有棱角,但第三方库的功能可以完成这件事。我已经克隆角文件上传通过混帐,但我仍然无法张贴一个简单的表格和文件。

有人可以提供一个例子,HTML以及如何做到这一点的JS?


解决方案

中首先


  1. 您不必在结构上的任何特殊变化。我的意思是:HTML input标签

\r
\r

<输入接受=图像/ *NAME =文件NG-值=fileToUploadVALUE ={{fileToUpload}}文件模式=fileToUpload设置文件的数据=fileToUpload =价值;类型=文件ID =my_file/>

\r

\r
\r

1.2创建自己的指令,

\r
\r

.directive(fileModel功能(){\r
返回{\r
限制:EA,\r
\t\t范围: {\r
setFileData:与&\r
},\r
链接:功能(范围,ELE,ATTRS){\r
ele.on('变',函数(){\r
范围。$应用(函数(){\r
变种VAL = ELE [0] .files [0];\r
scope.setFileData({值:VAL});\r
});\r
});\r
}\r
}\r
})

\r

\r
\r

<醇开始=2>
  • 在模块$ httpProvider添加依赖像的multipart / form-data的(接受,内容类型等)。 (建议是,接受JSON格式响应)
    对于例如:


  •   

    $ httpProvider.defaults.headers.post [接受] ='应用/ JSON,文字/ JavaScript的';
          $ httpProvider.defaults.headers.post ['内容类型'] ='的multipart / form-data的;字符集= UTF-8';


    <醇开始=3>
  • 然后创建控制器分离函数来处理表单提交的呼叫。
    像下面例如code:


  • 在服务功能手柄的responseType参数故意让服务器不应该抛出byteerror。


  • transformRequest,修改请求格式附加身份。


  • withCredentials:假的,用于HTTP认证信息


  • \r
    \r

    在控制器:\r
    \r
      fileUpload.uploadFileToUrl(文件); // code此相应,这样你的文件对象将在以下服务电话被拾起。\r
    \r
    \r
    \r
    服务:\r
    \r
      。服务('文件上传',['$ HTTP,ajaxService',\r
        功能($ HTTP,ajaxService){\r
    \r
          this.uploadFileToUrl =功能(数据){\r
            VAR数据= {}; //文件对象\r
    \r
            变种FD =新FORMDATA();\r
            fd.append(文件,data.file);\r
    \r
            $ http.post(端点服务器的路径给谁发送的文件,FD {\r
                withCredentials:假的,\r
                标题:{\r
                  内容类型:未定义\r
                },\r
                transformRequest:angular.identity,\r
                params:一个{\r
                  FD\r
                },\r
                的responseType:arraybuffer\r
              })\r
              .success(功能(响应,状态,头,配置){\r
                的console.log(响应);\r
    \r
                如果(状态== || 200 ==状态202)//做任何的成功\r
                否则//如果需要其他处理错误\r
              })\r
              .error(功能(错误,状态,头,配置){\r
                的console.log(错误);\r
    \r
                //处理其他电话\r
              });\r
          }\r
        }\r
      }])

    \r

    &LT;脚本src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js\"></script>\r
    \r
    \r

    I'm a beginner to angular.js but I have a have a good grasp of the basics.

    What I am looking to do is upload a file and some form data as multipart form data. I read that this isn't a feature of angular, however 3rd party libraries can get this done. I've cloned angular-file-upload via git, however I am still unable to post a simple form and a file.

    Can someone please provide an example, html and js of how to do this?

    解决方案

    First of all

    1. You don't need any special changes in the structure. I mean: html input tags.

    <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 create own directive,

    .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. In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format) For e.g:

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

    1. Then create separate function in controller to handle form submit call. like for e.g below code:

    2. In service function handle "responseType" param purposely so that server should not throw "byteerror".

    3. transformRequest, to modify request format with attached identity.

    4. withCredentials : false, for HTTP authentication information.

    in controller:
    
      fileUpload.uploadFileToUrl(file); //code this accordingly, so that your file object will be picked up in service call below.
    
    
    
    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"
              })
              .success(function(response, status, headers, config) {
                console.log(response);
    
                if (status == 200 || status == 202) //do whatever in success
                else // handle error in  else if needed 
              })
              .error(function(error, status, headers, config) {
                console.log(error);
    
                // handle else calls
              });
          }
        }
      }])

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

    这篇关于Angularjs如何上传多部分表单数据和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆