如何构建一个多MIME请求,并使用AngularJS'$ H​​TTP POST方法呢? [英] How to construct a multipart MIME request and POST it using AngularJS' $http method?

查看:140
本文介绍了如何构建一个多MIME请求,并使用AngularJS'$ H​​TTP POST方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何构建一个多部分MIME请求,并使用AngularJS $ HTTP方法发布到服务器API?

我试图将图像上传到服务器。图片的二进制数据应该是请求的体内的,使用POST方法和多MIME做的一部分。查询参数的其余部分可以被发送作为查询字符串参数,或者在多部分MIME作为其他部分。这里有一个请求应该是什么样子的捕获:

  POST https://webservice.platform.com/Service/V1/Service.ashx?Pictures_ProfilePhoto_Add HTTP / 1.1
PlatformSDK:xxxyyyzzz
主持人:webservice.platform.com
内容类型:多重/ form-data的;边界= --------------------------- 8d084109e6bc7e4
内容长度:1789
期望:100-继续
----------------------------- 8d084109e6bc7e4
内容处置:表格数据; NAME =应用程序名称name@domain.com - 示例应用程序
----------------------------- 8d084109e6bc7e4
内容处置:表格数据; NAME =ApplicationPasswordxxxxxnnnnnrrrqqqwwwssss
----------------------------- 8d084109e6bc7e4
内容处置:表格数据; NAME =UserTokenAABBCCDDEEFFGG
----------------------------- 8d084109e6bc7e4
内容处置:表格数据; NAME =ApplicationTag
----------------------------- 8d084109e6bc7e4
内容处置:表格数据; NAME =bytesFullPhotoData;文件名=bytesFullPhotoData
内容类型:应用程序/八位字节流JFIFxxC----------------------------- 8d084109e6bc7e4--


解决方案

以下code会得到你要的结果,但你应该使用指令的方法在下面的链接的http://odeto$c$c.com/blogs/scott/archive/2013/07/05/a-file-input-directive-for-angularjs.aspx

 <!DOCTYPE HTML>
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
< HEAD>
    < META HTTP-EQUIV =内容类型内容=text / html的;字符集= UTF-8>
    <标题>如何构建一个多MIME请求,并使用AngularJS'$ H​​TTP方法张贴<?/标题>
< /头>
<身体GT;
    &所述; SCRIPT SRC =htt​​p://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js>&下; /脚本>
    < D​​IV ID =为approot>
        < D​​IV NG控制器=TestCtrl>
            &所述p为H.;
                <输入类型=文本占位符=名称NG模型=的applicationName/>
                < BR />
                <输入类型=密码占位符=密码NG模型=applicationPassword/>
                < BR />
                <输入类型=文本占位符=令牌NG模型=userToken/>
                < BR />
                <输入类型=文本占位符=变量NG-模式=applicationTag/>
                < BR />
                <输入类型=文件的onchange =angular.element(本).scope()fileInputChanged(本);。 ID =的FileInput/>
            &所述; / P>
            <按钮式=按钮NG点击=uploadDocuments()>&上传LT; /按钮>
        < / DIV>
    < / DIV>    <脚本类型=文/ JavaScript的'>
        使用严格的;        VAR应用= angular.module('应用',[]);        app.controller('TestCtrl',函数($范围,$ HTTP){
            $ scope.filesToUpload = NULL;            $ scope.fileInputChanged =功能(元素){
                $范围。$应用(功能(适用范围){
                    scope.fileToUpload = element.files [0];
                });
            };            $ scope.uploadDocuments =功能(){
                VAR FORMDATA =新FORMDATA();
                formData.append(应用程序名称,$ scope.applicationName);
                formData.append(ApplicationPassword,$ scope.applicationPassword);
                formData.append(UserToken,$ scope.userToken);
                formData.append(ApplicationTag,$ scope.applicationTag);
                formData.append(BytesFullPhotoData,$ scope.fileToUpload);
                $ HTTP({
                    方法:POST,
                    网址:'/ API /图像/上传',//设置++自己的位置!
                    //如果你设置Content-Type的;边界=不会在头部所以设置不确定这将迫使浏览器,以填补
                    //点​​¯x头:{'内容类型':'的multipart / form-data的},
                    标题:{
                        内容类型:未定义
                    },
                    数据:FORMDATA,
                    transformRequest:功能(数据){
                        返回的数据;
                    }
                })成功(uploadComplete).error(uploadFailed);
            };            功能uploadComplete(数据,状态,头,配置){
                $ scope.filesToUpload = NULL;
                VAR的FileInput = $('#的FileInput');
                fileInput.replaceWith(=的FileInput fileInput.clone(真));
                的console.log(数据);
            }            功能uploadFailed(数据,状态,头,配置){
                的console.log(上传失败!');
            }        });        angular.element(文件)。就绪(函数(){
            angular.bootstrap(的document.getElementById('为approot'),['应用']);
        });
    < / SCRIPT>
< /身体GT;
< / HTML>

How do I construct a multipart MIME request and POST it to a server API using AngularJS $http method?

I am trying to upload an image to a server. The binary data of the picture should be part of the body of the request, done using the POST method and multipart MIME. The rest of the query parameters can be sent as query string parameters, or as other parts in the multipart MIME. Here's a capture of what a request should look like:

POST https://webservice.platform.com/Service/V1/Service.ashx?Pictures_ProfilePhoto_Add HTTP/1.1
PlatformSDK: xxxyyyzzz
Host: webservice.platform.com
Content-Type: multipart/form-data; boundary=---------------------------8d084109e6bc7e4
Content-Length: 1789
Expect: 100-continue


-----------------------------8d084109e6bc7e4
Content-Disposition: form-data; name="ApplicationName"

name@domain.com - Sample App
-----------------------------8d084109e6bc7e4
Content-Disposition: form-data; name="ApplicationPassword"

xxxxxnnnnnrrrqqqwwwssss
-----------------------------8d084109e6bc7e4
Content-Disposition: form-data; name="UserToken"

AABBCCDDEEFFGG
-----------------------------8d084109e6bc7e4
Content-Disposition: form-data; name="ApplicationTag"


-----------------------------8d084109e6bc7e4
Content-Disposition: form-data; name="bytesFullPhotoData"; filename="bytesFullPhotoData"
Content-Type: application/octet-stream

�����JFIF��x�x�����C�   

-----------------------------8d084109e6bc7e4--

解决方案

The following code will get the result you asked for but you should use directive approach as explained in following link http://odetocode.com/blogs/scott/archive/2013/07/05/a-file-input-directive-for-angularjs.aspx

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>How to construct a multipart MIME request and POST it using AngularJS' $http method?</title>
</head>
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
    <div id="appRoot">
        <div ng-controller="TestCtrl">
            <p>
                <input type="text" placeholder="Name" ng-model="applicationName" />
                <br />
                <input type="password" placeholder="Password" ng-model="applicationPassword" />
                <br />
                <input type="text" placeholder="Token" ng-model="userToken" />
                <br />
                <input type="text" placeholder="Tag" ng-model="applicationTag" />
                <br />
                <input type="file" onchange="angular.element(this).scope().fileInputChanged(this);" id="fileInput" />
            </p>
            <button type="button" ng-click="uploadDocuments()">Upload</button>
        </div>
    </div>

    <script type='text/javascript'>
        'use strict';

        var app = angular.module('app', []);

        app.controller('TestCtrl', function ($scope, $http) {
            $scope.filesToUpload = null;

            $scope.fileInputChanged = function (element) {
                $scope.$apply(function (scope) {
                    scope.fileToUpload = element.files[0];
                });
            };

            $scope.uploadDocuments = function () {
                var formData = new FormData();
                formData.append("ApplicationName", $scope.applicationName);
                formData.append("ApplicationPassword", $scope.applicationPassword);
                formData.append("UserToken", $scope.userToken);
                formData.append("ApplicationTag", $scope.applicationTag);
                formData.append("BytesFullPhotoData", $scope.fileToUpload);


                $http({
                    method: 'POST',
                    url: '/api/Image/Upload', //!++ Set your own location
                    // if you set Content-Type, ; boundary= won't be in header so set undefined which will force the browser to fill
                    //x headers: { 'Content-Type': 'multipart/form-data' },
                    headers: {
                        'Content-Type': undefined
                    },
                    data: formData,
                    transformRequest: function (data) {
                        return data;
                    }
                }).success(uploadComplete).error(uploadFailed);
            };

            function uploadComplete(data, status, headers, config) {
                $scope.filesToUpload = null;
                var fileInput = $('#fileInput');
                fileInput.replaceWith(fileInput = fileInput.clone(true));
                console.log(data);
            }

            function uploadFailed(data, status, headers, config) {
                console.log('Upload failed!');
            }

        });

        angular.element(document).ready(function () {
            angular.bootstrap(document.getElementById('appRoot'), ['app']);
        });
    </script>
</body>
</html>

这篇关于如何构建一个多MIME请求,并使用AngularJS'$ H​​TTP POST方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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