附加文件FORMDATA在angularjs无法正常工作 [英] append files to FormData not work in angularjs

查看:227
本文介绍了附加文件FORMDATA在angularjs无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用angularjs文件和JSON对象上传到单个请求服务器的NodeJS。然后,我得到这个萤火执行console.log:

  ----------------------------- 8791641017658内容处置:表格数据; NAME =模式 {\"phone\":\"asasasa\",\"description\":\"121212112\",\"payment\":\"2121212121\",\"shipping\":\"121221221\",\"imageurl\":\"21212112\",\"price\":\"212112212\",\"status\":\"new\"} ----------------------------- 8791641017658--

所以,名字=文件不会出现在这里。

而执行console.log(req.files)的服务器的NodeJS //打印出{}

请帮忙,谢谢!

  $ scope.files = [];        $范围。在(fileSelected$,功能(事件参数){        $范围。$应用(函数(){
            //文件对象添加到该范围内的文件集
            $ scope.files.push(args.file);
            的console.log($ scope.files);        });
        });    $ scope.create =功能(){
        $ scope.seller_submit = {
            电话:this.phone,
            说明:this.description,
            付款方式:this.payment,
            航运:this.shipping,
            图片网址:this.imageurl,
            价格:this.price,
            状态:this.status
        };        $ HTTP({
            方法:POST,
            网址:'/用品/+ $ routeParams.articleId,            标题:{'内容类型':未定义},            transformRequest:功能(数据){
                VAR FORMDATA =新FORMDATA();                formData.append(样板,angular.toJson(data.model));                对于(VAR I = 0; I< data.files;我++){                    formData.append(文件+我,data.files [I]);
                }
                返回FORMDATA;
            },            数据:{模式:$ scope.seller_submit,文件:$ scope.files}        })。
        成功(功能(数据,状态,头,配置){
            警报(成功!);
        })。
        错误(功能(数据,状态,头,配置){
            警报(失败!);
        });


解决方案

您可以创建一个服务

  myApp.service('uploadsService',函数($ HTTP){    变量code ='';
    变种文件名='';
    this.uploadFile =功能(文件){
        变种FD =新FORMDATA();        //在第一个选定的文件
        fd.append(形象,文件[0]);        VAR承诺= $ http.post('/上传/ uploadFile.json',FD {
                withCredentials:真实,
                标题:{'内容类型':未定义},
                transformRequest:angular.identity
            })。然后(功能(响应){            code = response.data code。
            文件名= response.data.fileName;            返回{
                code:功能(){
                    返回code;
                },
                文件名:函数(){
                    返回文件名;
                }
            };
        });
        返回的承诺;
    };  });

所以,你可以在你的控制器做这样的事情:

  $ scope.uploadFile =功能(文件){                    uploadsService.uploadFile(文件)。然后(功能(承诺){                        。$范围code =承诺code();
                        $ scope.fileName = promise.fileName();
     });   };

而在你的看法:

 <输入类型=文件的onchange =。angular.element(本).scope()uploadFile(this.files)NG模型=形象>

对我的作品:)

I use angularjs to upload files and json object to nodejs server in single request. Then I get this console.log on firebug:

-----------------------------8791641017658 Content-Disposition: form-data; name="model" {"phone":"asasasa","description":"121212112","payment":"2121212121","shipping":"121221221","imageurl":"21212112","price":"212112212","status":"new"} -----------------------------8791641017658--

So, the name="file" does not appear here.

And the console.log(req.files) in nodejs server // print out "{}"

Please help, thank!

$scope.files = [];

        $scope.$on("fileSelected", function (event, args) {

        $scope.$apply(function () {            
            //add the file object to the scope's files collection
            $scope.files.push(args.file);
            console.log($scope.files);

        });
        });

    $scope.create = function() {
        $scope.seller_submit = {
            phone: this.phone,
            description: this.description,
            payment: this.payment,
            shipping: this.shipping,
            imageurl: this.imageurl,
            price: this.price,
            status: this.status
        };

        $http({
            method: 'POST',
            url: '/articles/'+ $routeParams.articleId,

            headers: { 'Content-Type': undefined },

            transformRequest: function (data) {
                var formData = new FormData();

                formData.append("model", angular.toJson(data.model));

                for (var i = 0; i < data.files; i++) {

                    formData.append("file" + i, data.files[i]);
                }
                return formData;
            },

            data: { model: $scope.seller_submit, files: $scope.files }

        }).
        success(function (data, status, headers, config) {
            alert("success!");
        }).
        error(function (data, status, headers, config) {
            alert("failed!");
        });

解决方案

You could create a service for that

myApp.service('uploadsService', function($http) {   

    var code = '';
    var fileName = '';


    this.uploadFile = function(files) {


        var fd = new FormData();

        //Take the first selected file
        fd.append("image", files[0]);

        var promise =  $http.post('/uploads/uploadFile.json', fd, {
                withCredentials: true,
                headers: {'Content-Type': undefined },
                transformRequest: angular.identity
            }).then(function(response) {

            code = response.data.code;
            fileName = response.data.fileName;

            return{
                code: function() {
                    return code;
                },
                fileName: function() {
                    return fileName;
                }
            }; 
        });
        return promise;
    };

  });

So you could in your controller do something like:

    $scope.uploadFile = function(files) {

                    uploadsService.uploadFile(files).then(function(promise){

                        $scope.code = promise.code();
                        $scope.fileName = promise.fileName();
     });

   };

And in your view:

<input type="file" onchange="angular.element(this).scope().uploadFile(this.files)" ng-model="image">

Works for me :)

这篇关于附加文件FORMDATA在angularjs无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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