使用angular js将相机文件上传到sails.js服务器 [英] Upload camera file using angular js to sails.js server

查看:54
本文介绍了使用angular js将相机文件上传到sails.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用angular和sails进行简单的文件上传.我对所有这些技术都相当陌生.请问任何人告诉我我的代码有什么问题吗? 我使用以下命令创建了一个名为file的api文件:"sails generate api file"在我的sails服务器中,并且在控制器中我粘贴了此代码(

I'm trying to make a simple file upload using angular and sails.i am fairly new to all of these technolegies.could any of you please tell me what is wrong with my code? I have created an api called file using the command: "sails generate api file" in my sails server and in the controller i pasted this code(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);
        }
      };

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

next, i have made a function that takes a photo and displays it.now what i want to do is to send that file into my server and store it. here is my code:

   $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){

          })
      }
    }

推荐答案

我认为您的大多数代码都是正确的,但是一件非常重要的事情是,您应该在前面都给数据赋予相同的名称",端和后端.

Most of your codes are correct I think, but one thing which is very important that you should give the same "Name" of the data both on your front-end and the back-end.

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

In your case, the upload data name inside your back-end codes is "avatar":

 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()
     });
   });

但是,在前端代码中,帖子数据名称为图片".

However, inside the front-end codes the post data name is "image".

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

我认为这应该是阻止您的应用程序的主要问题.

I think this is should be the major issue which stopped your application.

这是一个如何使用angular比API远程上传文件的工作版本. http://jsfiddle.net/JeJenny/ZG9re/正在为我工​​作.

Here's a working version of how to use angular to upload file remotely than API http://jsfiddle.net/JeJenny/ZG9re/ which is working for me.

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

Below is my backend codes for you reference:

// 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
      });
    });
  }

};

这篇关于使用angular js将相机文件上传到sails.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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