【问题标题】:Upload camera file using angular js to sails.js server使用 Angular js 将相机文件上传到sails.js 服务器
【发布时间】:2014-10-14 21:40:00
【问题描述】:

我正在尝试使用 angular 和sails 进行简单的文件上传。我对所有这些技术都很陌生。你们中的任何人都可以告诉我我的代码有什么问题吗? 我在我的sails服务器和控制器中使用命令创建了一个名为file的api:“sails generate api file”,我粘贴了这段代码(https://github.com/sails101/file-uploads/blob/master/api/controllers/FileController.js#L15):

 /**
       * FileController
       *
       * @description :: Server-side logic for managing files
       * @help        :: See http://links.sailsjs.org/docs/controllers
       */

      module.exports = {



        /**
         * `FileController.upload()`
         *
         * Upload file(s) to the server's disk.
         */
        upload: function (req, res) {

          // e.g.
          // 0 => infinite
          // 240000 => 4 minutes (240,000 miliseconds)
          // etc.
          //
          // Node defaults to 2 minutes.
          res.setTimeout(0);

          req.file('avatar')
          .upload({

            // You can apply a file upload limit (in bytes)
            maxBytes: 1000000

          }, function whenDone(err, uploadedFiles) {
            if (err) return res.serverError(err);
            else return res.json({
              files: uploadedFiles,
              textParams: req.params.all()
            });
          });
        },

        /**
         * `FileController.s3upload()`
         *
         * Upload file(s) to an S3 bucket.
         *
         * NOTE:
         * If this is a really big file, you'll want to change
         * the TCP connection timeout.  This is demonstrated as the
         * first line of the action below.
         */
        s3upload: function (req, res) {

          // e.g.
          // 0 => infinite
          // 240000 => 4 minutes (240,000 miliseconds)
          // etc.
          //
          // Node defaults to 2 minutes.
          res.setTimeout(0);

          req.file('avatar').upload({
            adapter: require('skipper-s3'),
            bucket: process.env.BUCKET,
            key: process.env.KEY,
            secret: process.env.SECRET
          }, function whenDone(err, uploadedFiles) {
            if (err) return res.serverError(err);
            else return res.json({
              files: uploadedFiles,
              textParams: req.params.all()
            });
          });
        },


        /**
         * FileController.download()
         *
         * Download a file from the server's disk.
         */
        download: function (req, res) {
          require('fs').createReadStream(req.param('path'))
          .on('error', function (err) {
            return res.serverError(err);
          })
          .pipe(res);
        }
      };

接下来,我制作了一个拍摄照片并显示它的功能。现在我想做的是将该文件发送到我的服务器并存储它。这是我的代码:

   $scope.sendPost = function() {
    getPosts.getFoo('http://10.0.0.3:1337/user/create?name=temporaryUser&last_name=temporaryLastName4&title=' + 
      shareData.returnData()[0].title + '&content=' + shareData.returnData()[0].content + 
      '&image=' + /*shareData.returnData()[0].image*/ + '&category1=' + category1 + '&category2=' + 
      category2 + '&category3=' + category3 + '&category4=' + category4 + '&category5=' + category5 
      ).then(function(data) {
      $scope.items = data;
      console.log(shareData.returnData()[0]);
    });

      $scope.upload = function() {
          var url = 'http://localhost:1337/file/upload';
          var fd = new FormData();

          //previously I had this
          //angular.forEach($scope.files, function(file){
              //fd.append('image',file)
          //});

          fd.append('image', shareData.returnData()[0].image);

          $http.post(url, fd, {

              transformRequest:angular.identity,
              headers:{'Content-Type':undefined
              }
          })
          .success(function(data, status, headers){
              $scope.imageURL = data.resource_uri; //set it to the response we get
          })
          .error(function(data, status, headers){

          })
      }
    }

【问题讨论】:

    标签: angularjs sails.js ionic-framework


    【解决方案1】:

    我认为您的大多数代码都是正确的,但有一点非常重要,即您应该在前端和后端提供相同的数据“名称”。

    在您的情况下,您的后端代码中的上传数据名称是“头像”:

     req.file('avatar')
       .upload({
    
         // You can apply a file upload limit (in bytes)
         maxBytes: 1000000
    
       }, function whenDone(err, uploadedFiles) {
         if (err) return res.serverError(err);
         else return res.json({
           files: uploadedFiles,
           textParams: req.params.all()
         });
       });

    但是,在前端代码中,帖子数据名称是“图像”。

    fd.append('image', shareData.returnData()[0].image);

    我认为这应该是导致您的申请停止的主要问题。

    这是一个关于如何使用 Angular 远程上传文件的工作版本,而不是适用于我的 API http://jsfiddle.net/JeJenny/ZG9re/

    以下是我的后端代码供您参考:

    // myApp/api/controllers/FileController.js
    
    module.exports = {
    
      upload: function(req, res) {
        var uploadFile = req.file('file')
          //console.log(uploadFile);
        uploadFile.upload({
          dirname: sails.config.zdbconf.attachmentPath,
          maxBytes: 100000000
        }, function(err, files) {
          if (err)
            return res.serverError(err);
    
          return res.json({
            message: files.length + ' file(s) uploaded successfully!',
            files: files
          });
        });
      }
    
    };

    【讨论】:

    • 嗨,我有几个问题,sails.config.zdbconf.attachmentPath 的值是多少?它可能是我计算机中的任何文件夹路径吗?您在 Sails 项目中将变量 sails.config.zdbconf.attachmentPath 存储在哪里?提前致谢!
    猜你喜欢
    • 2014-11-16
    • 2016-01-28
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2017-06-05
    • 2017-07-04
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多