How to construct a multipart MIME request and POST it using AngularJS' $http method?

自古美人都是妖i 提交于 2019-12-22 18:43:19

问题


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--

回答1:


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>


来源:https://stackoverflow.com/questions/18930071/how-to-construct-a-multipart-mime-request-and-post-it-using-angularjs-http-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!