【问题标题】:Angular upload onchange event :getting empty file in server角度上传 onchange 事件:在服务器中获取空文件
【发布时间】:2017-06-23 19:10:23
【问题描述】:

这是我在输入更改时将文件上传到服务器的代码

    $scope.uploadImage = function (f) { 
        $http.post('/art',{'image':f},{headers: {'Content-Type': undefined}}).then(function (response) {
            console.log(response);
        }); 
    }

但是我会在服务器中获得空文件但是我使用正常的文件上传检查我的服务器端代码它可以正常工作,没有任何问题

服务器端

//get empty in angular upload 
     console.log(req.file('image'));

        req.file('image').upload({
                // don't allow the total upload size to exceed ~10MB
                maxBytes: 10000000
            },function whenDone(err, uploadedFiles) {

            return res.json({
                'status':uploadedFiles
            })
        }); 

HTML

<input type="file" ng-model="art.artImage" onchange="angular.element(this).scope().uploadImage(this.files)" name="artImage" id="artImage">

我认为 content-type 在 Angular http post 请求中存在问题

【问题讨论】:

  • 调试$scope.uploadImage函数时看到的“f”的值是多少。
  • Json 对象包含像这样的文件信息1 0 : File lastModified : 1493977671608 lastModifiedDate : Fri May 05 2017 15:17:51 GMT+0530 (IST) __proto__ : Object name : "1493977658097.jpeg" size : 10286 type : "image/jpeg" webkitRelativePath : "" __proto__ : File
  • @Jabaa 你能用f 代替{'image':f} 吗?这可能会导致内容类型更改为 application/json。
  • @StanislavKvitash 还是同样的错误
  • @Jabaa 你有什么错误?你检查过内容类型吗?在这种情况下是什么?

标签: javascript angularjs node.js sails.js


【解决方案1】:

当输入类型为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]);
            });
        }
    }
}]);

像这样改变输入

<input type="file" fileread="art.artImage" onchange="angular.element(this).scope().uploadImage(this.files)" 
name="artImage" id="artImage">

在您的请求中使用multipart 标头

$http.post('/art', {
    'image': art.artImage
}, {
    transformRequest: angular.identity,
    headers: {
        'Content-Type': "multipart/form-data"
    }
})

【讨论】:

  • 让我试试你的答案
  • 它也不起作用,我的内容类型仍然是 application/json 它没有改变
  • 现在内容类型改变了,但仍然是空结果
【解决方案2】:

为 angularjs 使用 ng-fileUpload lib

我的 HTML

<form  method="post" enctype="multipart/form-data" ng-controller="commentCtrl" name="form">
    <a href="" type="file" class="custom-height"><img src="source/assets/images/icons/icofileattached.png" class="attachmentpng-height"  ngf-select="uploadFiles($file)" ng-model="files"/></a>
    <md-button type="submit" class="md-raised custom-submit-button" ng-click="MakeComments()"> SUBMIT </md-button>
    </form>

我的控制器代码

$scope.uploadFiles = function(file) {
            console.log(file);
            $scope.fileData = file;
            var fd = new FormData();
            fd.append('file', file);
            Restangular.one('/api/files/end points').withHttpConfig({transformRequest: angular.identity})
                .customPOST(fd, '', undefined, {'Content-Type': undefined})
        };

【讨论】:

    【解决方案3】:

    请试试这个,避免在文件的 HTML 标记中使用 onload:

    <html>
     <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
       </head>
    
       <body ng-app = "myApp">
    
      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>
    
      <script>
         var myApp = angular.module('myApp', []);
    
         myApp.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]);
                     });
                  });
               }
            };
         }]);
    
         myApp.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
               var fd = new FormData();
               fd.append('file', file);
    
               $http.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })            
               .success(function(){
                   alert("Done");
               })            
               .error(function(){
                   alert("Sorry");
               });
            }
         }]);
    
         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;
    
               console.log('file is ' );
               console.dir(file);
    
               var uploadUrl = "/art";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);
    
      </script>
    
       </body>
    </html>
    

    【讨论】:

    • 尝试了同样的错误表单数据得到空对象
    • 根据您在 cmets 中解释的 json,我想您将不得不使用文件名而不是整个文件对象。所以请使用 "f.name" 而不是 "f" 。您的文件名是“1493977658097.jpeg”,“f”的 JSON 有 {.....name : "1493977658097.jpeg"...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 2021-09-09
    相关资源
    最近更新 更多