简体   繁体   English

Angular JS“表单多部分”文件上传将未定义的值发送到服务器。 无法将文件上传到Java服务器

[英]Angular JS “form Multi-part” file upload sending Undefined value to server. Cannot upload file to Java Server

I have the following HTML. 我有以下HTML。

    <form >
        <input type="file" file-model="myFile"/>
       <button ng-click="uploadFile()">upload me</button>
   </form>

And inside controller I have following function 在控制器内部我有以下功能

$scope.uploadFile = function() {
        var file = $scope.myFile; //when I try console.log(file...it says undefined)
       var fd = new FormData();
        fd.append('file', file);
        $http.post("url", fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined},
                transformResponse: [function (data) {
                    return data;
                }]
            }).then(function (result) {
            console.log(result.data);
        })
    }

the Directives I have is 我的指令是

 .directive('fileModel', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;

                element.bind('change', function(){
                    scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                    });
                });
            }
        };
    }]);

For some reason, I am not getting the file value. 由于某种原因,我没有得到文件值。 On console.log() I am receiving undefined. 在console.log()上,我收到未定义的信息。 FYI, I am just trying to grab a file. 仅供参考,我只是想获取一个文件。 Is there something wrong in my code? 我的代码有问题吗?

I came to that conclusion because it seems to have passing undefined to server from browser's developer tool. 我之所以得出这个结论,是因为它似乎已经从浏览器的开发人员工具向服务器传递了未定义的消息。 The screen-grab is as follows. 屏幕抓取如下。 在此处输入图片说明

The problem was non binding issue with files. 问题是文件的非绑定问题。 Angular has no support for that yet. Angular还没有支持。 It was solved with the solution provided here. 使用此处提供的解决方案解决了该问题。 AngularJs: How to check for changes in file input fields? AngularJs:如何检查文件输入字段中的更改?

This worked for me: 这对我有用:

<div>
    <input id="imageList" name="imageList" type="file" file-model="myFile">
</div>

I also had a json object to send with the form: 我也有一个JSON对象以以下形式发送:

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      formData.append("file", file);
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM