如何在AngularJs中将<input file =“”/>编码为base64?

时间:2013-07-09 13:49:35

标签: javascript drupal

我需要通过drupal服务/文件将图像保存到Drupal中。据我所知,我需要将文件解码为base64并将其作为服务/文件的有效负载发送。我怎么能编码才能做到这一点????我想在javascript中这样做。

6 个答案:

答案 0 :(得分:26)

我是@GrimurD提到的angular-base64-upload的作者。该指令适用于此场景。它将图像(或任何其他文件类型)解析为base64编码,并将文件信息附加到示波器中的模型。

样本用法:

<input type='file' ng-model='yourModel' base-sixty-four-input>

选择文件后,yourModel的值将为:

{
  "filetype": "text/plain",
  "filename": "textfile.txt",
  "base64": "/asdjfo4sa]f57as]fd42sdf354asdf2as35fd4"
}

它还提供了使用PHP或ruby解码服务器中base64文件的示例代码。

答案 1 :(得分:11)

我知道它已经很老了,但是我来这里寻求解决方案。

最后我发现(如果你不想使用外部库)在base 64中加载图像就像使用javascript FileReader.readAsDataURL()

一样简单

希望我的最终代码能够帮助像我这样的其他初学者。它的特点是:

  • 输入带有HTML5 input type='file'的文件(灵感来自this answer
  • 从其他html元素触发输入(受this answer启发)
  • 检查浏览器是否支持input type='file'(灵感来自this answer

也在codepen

angular.module('starter', [])
  .controller('Ctrl', function($scope) {
    $scope.data = {}; //init variable
    $scope.click = function() { //default function, to be override if browser supports input type='file'
      $scope.data.alert = "Your browser doesn't support HTML5 input type='File'"
    }

    var fileSelect = document.createElement('input'); //input it's not displayed in html, I want to trigger it form other elements
    fileSelect.type = 'file';

    if (fileSelect.disabled) { //check if browser support input type='file' and stop execution of controller
      return;
    }

    $scope.click = function() { //activate function to begin input file on click
      fileSelect.click();
    }

    fileSelect.onchange = function() { //set callback to action after choosing file
      var f = fileSelect.files[0],
        r = new FileReader();

      r.onloadend = function(e) { //callback after files finish loading
        $scope.data.b64 = e.target.result;
        $scope.$apply();
        console.log($scope.data.b64.replace(/^data:image\/(png|jpg);base64,/, "")); //replace regex if you want to rip off the base 64 "header"

        //here you can send data over your server as desired
      }

      r.readAsDataURL(f); //once defined all callbacks, begin reading the file

    };


  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>

<body ng-app='starter' ng-controller='Ctrl'>
  <button ng-click='click()'>click to select and get base64</button>
  <br>BASE 64 data:
  <br>
  <span style='color: red'>{{data.alert}}</span>
  <div style='word-wrap:break-word'>
    {{data.b64}}
  </div>
</body>

答案 2 :(得分:8)

我建议你使用https://github.com/ninjatronic/angular-base64

按照使用此库的说明后,您只需致电:

var imageData=$base64.encode(image);

别忘了注入你的模块:

.module('myApp', ['base64'])

答案 3 :(得分:0)

你不需要AngularJs。这里有一个帖子解释如何使用Javascript和canvas进行操作:How to convert image into base64 string using javascript

答案 4 :(得分:0)

答案 5 :(得分:0)

我遇到了同样的问题并遇到了this repository on github。试了一下,它运作得很好。