javascript 如何在 AngularJs 中将 <input file> 编码为 base64?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17549968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:43:59  来源:igfitidea点击:

How to Encode an <input file> to base64 in AngularJs?

javascriptdrupal

提问by Poncho1984

I need to save an image into Drupal, through the drupal service/file. For what i understand i need to decode the file into a base64 and send this as a payload for the service/file. How can i get to encode the in order to do this???? I want to do this in javascript.

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

回答by Adones Pitogo

I am the author of angular-base64-uploadas mentioned by @GrimurD. This directive works perfectly for this scenario. It parses image(or any other file types) into base64-encoding and attach the file info to a model in your scope.

我是@GrimurD 提到的angular-base64-upload的作者。该指令非常适合这种情况。它将图像(或任何其他文件类型)解析为 base64 编码并将文件信息附加到您范围内的模型。

Sample usage:

示例用法:

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

Once you selected a file, yourModelwill have a value of something like:

一旦你选择了一个文件,yourModel将有一个类似的值:

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

It also has sample code for decoding the base64 file in your server, using PHP or ruby.

它还包含使用 PHP 或 ruby​​ 解码服务器中 base64 文件的示例代码。

回答by Karlooie

I know it's quite old, but I came here for a solution.

我知道它很旧,但我来这里是为了解决问题。

In the end I found out that (if you don't want to use external libraries) loading an image in base 64 is as simple as using javascript FileReader.readAsDataURL()

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

Hopefully my final code will help others beginners like me. It features:

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

  • Input file with HTML5 input type='file'(inspired by this answer)
  • Trigger input from other html elements (inspired by this answer)
  • Check if browser supports input type='file'(inspired by this answer)
  • 带有 HTML5 的输入文件input type='file'(受此答案启发)
  • 触发来自其他 html 元素的输入(受此答案启发)
  • 检查浏览器是否支持input type='file'(受此答案启发)

It is also on codepen

它也在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>

回答by Bipin Bhandari

I would recommend you to use https://github.com/ninjatronic/angular-base64.

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

After following instructions for using this library, you can simply call:

按照使用此库的说明进行操作后,您只需调用:

var imageData=$base64.encode(image);

Don't forget to inject in your module:

不要忘记注入你的模块:

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

回答by grimurd

I was having the same problem and ran into this repository on github. Tried it out and it worked perfectly.

我遇到了同样的问题,并在 github 上遇到了这个存储库。试了一下,效果很好。

回答by Reason

You don't need AngularJs for that. There is a thread here explaining how to do it using Javascript and canvas: How to convert image into base64 string using javascript

你不需要 AngularJs。这里有一个线程解释了如何使用 Javascript 和 canvas:How to convert image into base64 string using javascript