Send FormData with other field in AngularJS

前端 未结 5 1089
天涯浪人
天涯浪人 2020-11-28 09:46

I have a form with two input text and one upload. I have to send it to the server but I have some problem concatenating the file with the text. The

5条回答
  •  情歌与酒
    2020-11-28 10:43

    Using $resource in AngularJS you can do:

    task.service.js

    $ngTask.factory("$taskService", [
        "$resource",
        function ($resource) {
            var taskModelUrl = 'api/task/';
            return {
                rest: {
                    taskUpload: $resource(taskModelUrl, {
                        id: '@id'
                    }, {
                        save: {
                            method: "POST",
                            isArray: false,
                            headers: {"Content-Type": undefined},
                            transformRequest: angular.identity
                        }
                    })
                }
            };
        }
    ]);
    

    And then use it in a module:

    task.module.js

    $ngModelTask.controller("taskController", [
        "$scope",
        "$taskService",
        function (
            $scope,
            $taskService,
        ) {
        $scope.saveTask = function (name, file) {
            var newTask,
                payload = new FormData();
            payload.append("name", name);
            payload.append("file", file);
            newTask = $taskService.rest.taskUpload.save(payload);
            // check if exists
        }
    }
    

提交回复
热议问题