Upload camera file using angular js to sails.js se

2019-08-07 09:34发布

问题:

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

          })
      }
    }

回答1:

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.

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

};