Pon*_*984 15 javascript drupal
我需要通过drupal服务/文件将图像保存到Drupal中.据我所知,我需要将文件解码为base64并将其作为服务/文件的有效负载发送.我怎么能编码才能做到这一点???? 我想在javascript中这样做.
Ado*_*ogo 27
我是@GrimurD提到的angular-base64-upload的作者.该指令适用于此场景.它将图像(或任何其他文件类型)解析为base64编码,并将文件信息附加到范围中的模型.
样品用法:
<input type='file' ng-model='yourModel' base-sixty-four-input>
Run Code Online (Sandbox Code Playgroud)
选择文件后,yourModel
将具有以下值的值:
{
"filetype": "text/plain",
"filename": "textfile.txt",
"base64": "/asdjfo4sa]f57as]fd42sdf354asdf2as35fd4"
}
Run Code Online (Sandbox Code Playgroud)
它还有使用PHP或ruby解码服务器中base64文件的示例代码.
小智 11
我知道它已经很老了,但我来这里寻求解决方案.
最后我发现(如果你不想使用外部库)在base 64中加载图像就像使用javascript FileReader.readAsDataURL()一样简单
希望我的最终代码能够帮助像我这样的其他初学者.它的特点是:
它也在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
};
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
我建议你使用https://github.com/ninjatronic/angular-base64.
按照使用此库的说明后,您只需调用:
var imageData=$base64.encode(image);
Run Code Online (Sandbox Code Playgroud)
不要忘记注入你的模块:
.module('myApp', ['base64'])
Run Code Online (Sandbox Code Playgroud)
你不需要 AngularJs。这里有一个线程解释如何使用 Javascript 和 canvas 来做到这一点:How to conversion image into base64 string using javascript
归档时间: |
|
查看次数: |
53712 次 |
最近记录: |