Angular js图片上传

时间:2016-02-09 11:41:11

标签: angularjs node.js image upload

我在前端生成一些图像,我想将它们直接发送到后端进行进一步处理。如何在不使用表单数据的情况下执行此操作?有什么选择吗?

图像是从画布(实际上是打印屏幕)生成的,应该在生成时发布到服务器。

我将Node js用于后端(Express服务器),将Angular用于前端。

欢迎任何帮助或见解!

提前致谢。

1 个答案:

答案 0 :(得分:1)

所以你需要:

  1. 在画布上绘图

    var canvas = document.createElement('canvas');
    canvas.width = 600;
    canvas.height = 600;
    var context = canvas.getContext('2d');
    
    context.beginPath();
    context.moveTo(100, 150);
    context.lineTo(450, 50);
    context.lineWidth = 10;
    
    // set line color
    context.strokeStyle = '#ff0000';
    context.stroke();
    
  2. 将画布数据编码为您选择的格式(比如jpg)

    function dataURItoBlob(dataURI) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {
        type: 'image/jpeg'
      });
    }
    
    function canvasToJPG(cvs, done) {
      var quality = 90; // jpeg quality
    
      if (cvs.toBlob) // some browsers has support for toBlob
        cvs.toBlob(done, 'image/jpeg', quality / 100);
      else
        done(dataURItoBlob(cvs.toDataURL('image/jpeg', quality / 100)));
    }
    
  3. 使用AngularJS $http

    在线路上发送
    $http
    ({
        method: 'POST',
        url: '/upload',
        headers: {'Content-Type': 'image/jpeg'},
        data: data,
        transformRequest: []
    })
    .success(function ()
    {
        alert('image uploaded :)');
    })
    .error(function (err)
    {
        console.log('upload error',err);
        alert('something went wrong :( ');
    });
    
  4. 4A。从节点上的ExpressJS路由获取它(比如在fs上流式传输)

        app.post('/upload', function(req, res, next) {
          var wstream= fs.createWriteStream('uploaded.jpg'); // say you want to write the file to disk
    
          req.pipe(wstream) // pipe the http request body to the file stream
             .on('error',next) // something went wrong with the fs, return 500
             .on('finish',function () {
                 res.status(204).send(); // success!
             });
        });
    

    4b中。从节点上的ExpressJS路由获取它(比如你想要原始的JPG缓冲区)

        app.post('/upload', function(req, res, next) {
          var buff= [];
    
          req.on('data',function (data)
             {
                buff.push(data);
             })
             .on('error',next) 
             .on('end',function () {
                 fs.writeFile('uploaded.jpg',Buffer.concat(buff),function (err)
                 {
                     if (err) return next(err); // something went wrong with the fs, return 500
    
                     res.status(204).send(); // success!
                 });
             });
        });
    

    完整的样本:

    var myapp = angular.module('myapp', []);
    
    myapp.controller('upload', function($scope, $http) {
      $scope.drawAndUpload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = 600;
        canvas.height = 600;
        var context = canvas.getContext('2d');
    
        context.beginPath();
        context.moveTo(100, 150);
        context.lineTo(450, 50);
        context.lineWidth = 10;
    
        // set line color
        context.strokeStyle = '#ff0000';
        context.stroke();
    
        var upload = function(data) {
          $http
            ({
              method: 'POST',
              url: '/upload',
              headers: {
                'Content-Type': 'image/jpeg'
              },
              data: data,
              transformRequest: []
            })
            .success(function() {
              alert('image uploaded :)');
            })
            .error(function(err) {
              console.log('upload error', err);
              alert('something went wrong :( ');
            });
        };
    
        canvasToJPG(canvas, upload);
      };
    });
    
    function dataURItoBlob(dataURI) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {
        type: 'image/jpeg'
      });
    }
    
    function canvasToJPG(cvs, done) {
      var quality = 90; // jpeg quality
    
      if (cvs.toBlob) // some browsers has support for toBlob
        cvs.toBlob(done, 'image/jpeg', quality / 100);
      else
        done(dataURItoBlob(cvs.toDataURL('image/jpeg', quality / 100)));
    }
    <html>
    
    <head>
      <title>My Angular App</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
      <script src="app.js"></script>
    </head>
    
    <body ng-app="myapp" ng-controller="upload">
      <button ng-click="drawAndUpload()">Draw & Upload</button>
    </body>
    
    </html>

    var express = require('express'),
        fs = require('fs');
    var app = express();
    
    app.use(express.static('www'));
    
    app.post('/upload', function(req, res, next) {
      var buff= [];
    
      req.on('data',function (data)
         {
            buff.push(data); 
         })
         .on('error',next) // something went wrong with the fs, return 500
         .on('end',function () {
             fs.writeFile('uploaded.jpg',Buffer.concat(buff),function (err)
             {
                 if (err) return next(err);
    
                 res.status(204).send(); // success!
             });
         });
    });
    
    app.listen(8080);