使用angular.js提交<input type =“”file“/”/>,如何将text / plain转换为multipart / form-data?

时间:2017-11-02 14:08:22

标签: javascript angularjs

我的问题与File Upload using AngularJS不同 我有文件的数据。但是当请求时,内容类型是text / plain,但我需要multipart / form-data。那我怎么转换?代码有什么问题? here is what console showed

HTML:

<form ng-submit="processForm()" enctype="multipart/form-data">
    <div class="form-group">
        <label class="label"><span class="tip" ng-hide="data.id">*</span>ID:</label>
        <input class="input" name="id" ng-model="data.id" maxlength="5">
    </div>
    <div class="form-group">
        <input type="file" name="preview" fileread="data.preview">
    </div>
    <button type="submit" class="btn btn-default btn-small">save</button>
</form>

js:ng-model for <input type="file"/>

.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}]);

点击提交时:

$scope.processForm = function(){
    var data = $scope.data,
        url = Api.add,
        config;
    $http({
        method: 'POST',
        url: url,
        data: data,
        headers: {'Content-Type': undefined},
     }).then(function(result){

0 个答案:

没有答案