angularjs - 如何将 AngularJS 中的文件和表单数据发送到 Node.js 服务器?

标签 angularjs node.js express

你好,我正在创建视频上传表单的平均应用程序。当我在 Angular JS 中将请求发布到我的 api 时,我碰到一个地方,然后没有数据发送到我的 Controller 。我哪里做错了??

<form ng-submit="uploadComplete(form)" enctype="multipart/form-data" id="myForm"  ng-controller = "addCtrl">

<div class="form-group">
  <label >Title</label>
  <input type="text" class="form-control" ng-model = "form.title" name="title" placeholder="Enter Title">
</div>
<div class="form-group">
  <label >Description</label>
  <textarea class="form-control" ng-model= "form.description"  name ="description" rows="5" id="comment" placeholder="Enter Description"></textarea>
</div>
<div class="form-group">
  <label >Author</label>
  <input type="text" class="form-control" ng-model = "form.author"  name ="author" id="exampleInputPassword1" placeholder="Enter Author Name">
</div>
<div class="form-group">
  <label >duration</label>
  <input type="text" class="form-control" ng-model = "form.duration"  name ="duration" id="exampleInputPassword1" placeholder="Enter duration Name">
</div>
<div class="form-group">
  <label >ispublic</label>
  <input type="text" class="form-control" ng-model = "form.public"  name ="public" id="exampleInputPassword1" >
</div>



<input type="file" onchange="angular.element(this).scope().fileChanged(this)" id="userfile" name="userfile" multiple/>


  <input type="submit" name="" value="submit">

我的 Angular Controller 是

function addCtrl($scope, $filter, editableOptions,$http, editableThemes,$window,$uibModal, baProgressModal) {
      $scope.fileChanged = function(elem){
        $scope.files = elem.files;
        $scope.$apply();
      }
  $scope.uploadComplete = function(f){

  $http({
    method: 'POST',
    format: 'json',
    url: '/api/add-video',
    headers: {
                'Content-Type': 'multipart/form-data'
            },
    data: JSON.stringify({
      title: f.title,
      description: f.description,
      duration: f.duration,
      author:f.author,

      file:$scope.files,
      ispublic:parseInt(f.public)
    }),
    transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                var headers = headersGetter();
                delete headers['Content-Type'];

                return formData;
            }

  })
  .then(function(success) {
    console.log("hit " + JSON.stringify(success));
    // $window.location.reload()
  }, function(error) {
    //console.log("not hit " + JSON.stringify(error));
  });

   }
  console.log($scope.files[0].name);
  console.log(parseInt(f.public));
  }

  }
  })();

和我的 api/url,它是服务器端的一部分

app.post('/api/add-video', addVideoHandler);
function addVideoHandler(req, res) {

  var data = {
    title: req.body.title,
    description: req.body.description,
    author: req.body.author,
    duration: req.body.duration,
    file: req.body.file,
    ispublic: req.body.ispublic
  }
console.log(data);

}

我已经使用了上面的 url 文件中的所有 Node 包,但我没有提到。为什么我没有在它显示的控制台中获取所有数据:

 { title: undefined,
  description: undefined,
  author: undefined,
  duration: undefined,
  file: undefined,
  ispublic: undefined }

我哪里做错了? 请指导我。谢谢

最佳答案

尝试使用如下指令

.directive('fileModel', ['$parse', function($parse) {
        function fn_link(scope, element, attrs) {
            var onChange = $parse(attrs.fileModel);
            element.on('change', function (event) {
                onChange(scope, { $files: event.target.files });
            });
        };
        return {
            link: fn_link
        }
    }])

然后将输入类型=文件替换为

<input type="file" class="form-control" id="fileId" accept="image/*" file-model="myFiles($files)"/>

然后在你的 Controller 中添加这个

var formData = new FormData();
        $scope.myFiles = function($files) {
            formData.append('img', $files[0]);
}

将“img”替换为您希望在后端使用的名称 使用 formData 中的键添加每个值以进行发送

formData.append('title', form.title);
formData.append('description', form.description);
formData.append('author', form.author);
formData.append('duration', form.duration);
formData.append('public', form.public);

和你的 $http 方法

  $http({
    method: 'POST',
    url: '/api/add-video',
    headers: {
                'Content-Type': undefined
            },
    data: **formData**),

Node 端 然后使用 multer diskStorage 作为将文件上传到服务器

var uploadMulter = multer.diskStorage({
     destination: function(req, file, callback) {
         callback(null, "./UploadDir");
     },
     filename: function(req, file, callback) {
         callback(null,  Date.now() + path.extname(file.originalname));
     }
 });

var upload = multer({ storage: uploadMulter });

./UploadDir 是您要上传文件的目标文件夹

最后是你的路由器

app.post('/api/add-video',  upload.single('img'), addVideoHandler);

现在,如果您想上传单个文件,请使用 upload.single('img') ** 或多次使用 **upload.array('img',3) 这里将上传 3 个文件。随心所欲地改变。

这是我在 StackOverflow 上的第一个回答:-)

如果您的目标目录 UploadDir 不可访问,请尝试通过以下方式加入

app.use('/UploadDir', express.static(path.join(__dirname, 'UploadDir')))

如果不起作用,请尝试此 $http 方法

$http.post('/api/add-video',formData,{headers:{'Content-Type': undefined}})

将 Controller 更改为

.controller('addCtrl', function($scope,$http){
var formData = new FormData();
 $scope.myFiles = function($files) {
  formData.append('img', $files[0]);
  }
$scope.uploadComplete= function(form){
  formData.append('title', form.title);
  formData.append('description', form.description);
  formData.append('author', form.author);
  formData.append('duration', form.duration);
  formData.append('public', form.public);
  $http.post('/api/add-video',formData,{headers:{'Content-Type': undefined}}).then(function(res){
    alert("Correctly Done")
   }, function(err){
   alert("Error check console in browser");
    console.log(err)
    })
  }
})

关于angularjs - 如何将 AngularJS 中的文件和表单数据发送到 Node.js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212679/

相关文章:

node.js - 如何使用 "cors"库在 Express Route 上配置 CORS

node.js - API.ai/Dialogflow 基本文本请求不起作用

javascript - Json 对象变得扁平化

javascript - Angular 单元测试 : Calling a method defined in another controller is throwing 'undefined' is not an error

javascript - 手动安装 mysql2 包 - 错误

javascript - 如何在 Angular JS 中持久化数据和模型

node.js - 如何在 Node-Express/Vue Web 应用程序中管理 OAuth?

node.js - Nginx 用于 Node JS 应用程序中的身份验证和授权

javascript - 在angularjs中为这个HTTP GET添加HTTP基本认证

javascript - 在 Angular 中设置上下文范围