My problem is that i need to upload big videos files, but not that big. like 100~500mb. videos with 70mb i can do it. when i try to upload a large file, firefox crashes and closes. the same happen with chrome. I'm using html5uploader.js.
/*
* Upload files to the server using HTML 5 Drag and drop the folders on your local computer
* Tested on: Mozilla Firefox 3.6.12, Google Chrome 7.0.517.41, Safari 5.0.2, WebKit r70732
* The current version does not work on: Opera 10.63, Opera 11 alpha, IE 6+.
*/
function uploader(place, status, targetPHP, show) {
// Upload image files
upload = function(file) {
if((file.type == 'image/jpeg' || file.type == 'audio/mpeg' || file.type =='image/png' || file.type == 'image/bmp' || file.type == 'image/gif')){
alert('Arquivo não permitido.');
return false;
}
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', targetPHP+'?up=true', true);
var boundary = 'xxxxxxxxx';
var body = '--' + boundary + "\r\n";
// body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + encodeURI(file.name) + "'\r\n";
body += "Content-Type: " + file.type + "\r\n\r\n";
body += bin + "\r\n";
body += '--' + boundary + '--';
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
// Chrome 7 sends data but you must use the base64_decode on the PHP side
} else {
xhr.open('POST', targetPHP+'?up=true&base64=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
}
if (show) {
var newFile = document.createElement('div');
tamanho = (((file.size)/1024)/1024);
tamanhoMB = tamanho.toFixed(2);
newFile.innerHTML = 'Nome do arquivo: ' + file.name+ ' | Tamanho: '+tamanhoMB+' MB';
document.getElementById(show).appendChild(newFile);
}
if (status) {
document.getElementById(status).innerHTML = 'Upload concluído! Arraste o próximo arquivo.';
}
};
// Loading errors
this.loadError = function(event) {
switch(event.target.error.code) {
case event.target.error.NOT_FOUND_ERR:
document.getElementById(status).innerHTML = '<h4>Arquivo não encontrado!</h4>';
break;
case event.target.error.NOT_READABLE_ERR:
document.getElementById(status).innerHTML = '<h4>Arquivo não legível!</h4>';
break;
case event.target.error.ABORT_ERR:
break;
default:
document.getElementById(status).innerHTML = '<h4>Erro de leitura.</h4>';
}
};
// Reading Progress
this.loadProgress = function(event) {
if (event.lengthComputable) {
var percentage = Math.round((event.loaded * 100) / event.total);
document.getElementById(status).innerHTML = '<h4>Carregando... '+percentage+'%</h4>';
}
};
// Preview images
this.previewNow = function(event) {
bin = preview.result;
var img = document.createElement("img");
img.className = 'addedIMG';
img.file = file;
img.src = bin;
document.getElementById(show).appendChild(img);
};
reader = new FileReader();
// Firefox 3.6, WebKit
if(reader.addEventListener) {
reader.addEventListener('loadend', this.loadEnd, false);
if (status != null)
{
reader.addEventListener('error', this.loadError, false);
reader.addEventListener('progress', this.loadProgress, false);
}
// Chrome 7
} else {
reader.onloadend = this.loadEnd;
if (status != null)
{
reader.onerror = this.loadError;
reader.onprogress = this.loadProgress;
}
}
var preview = new FileReader();
// Firefox 3.6, WebKit
if(preview.addEventListener) {
preview.addEventListener('loadend', this.previewNow, false);
// Chrome 7
} else {
preview.onloadend = this.previewNow;
}
// The function that starts reading the file as a binary string
reader.readAsBinaryString(file);
// Preview uploaded files
if (show) {
preview.readAsDataURL(file);
}
// Safari 5 does not support FileReader
} else {
xhr = new XMLHttpRequest();
xhr.open('POST', targetPHP+'?up=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(file);
if (status) {
document.getElementById(status).innerHTML = '100% carregado';
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = file.name+' (Tamanho: '+file.size+' Bytes)';
document.getElementById(show).appendChild(newFile);
}
}
};
// Function drop file
this.drop = function(event) {
event.preventDefault();
var dt = event.dataTransfer;
var files = dt.files;
if (files.length<=2){
for (var i = 0; i<files.length; i++) {
var file = files[i];
upload(file);
}
}else{
alert('Limite de upload excedido! Máximo permitido: dois arquivos.');
}
};
// The inclusion of the event listeners (DragOver and drop)
this.uploadPlace = document.getElementById(place);
this.uploadPlace.addEventListener("dragover", function(event) {
event.stopPropagation();
event.preventDefault();
}, true);
this.uploadPlace.addEventListener("drop", this.drop, false);
}
i read a lot of questions and posts with a similar problem, but nothing seems to work here. i dont know what else i can do. i change the variables to these values both on wamp\bin\php\php5.3.5\php.ini, wamp\bin\apache\Apache2.2.17\bin\php.ini and wamp\bin\php\php5.3.5\phpForApache.ini:
upload_max_filesize -> 1024mb,
post_max_size -> 1024mb,
max_execution_time -> 600,
max_input_time -> 600,
memory_limit -> 2048mb.
Restart wamp, didnt work. On wamp\bin\apache\Apache2.2.17\conf\extra\httpd-vhosts.conf i put the following:
<Directory "D:\wamp\www\projec">
LimitRequestBody 102400
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Also didnt work. anyone has a solution or idea to save me? I really appreciate. Thanks.
Related
Following this link, I just change the webm format to fMP4 as below. But it doesn't work. The original test.webm file works fine.
for webm, the config as below:
//source: http://html5-demos.appspot.com/static/test.webm
var FILE = "test.webm"
var codec = 'video/webm; codecs="vorbis,vp8"';
for fMP4, change the config as below:
//source http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-85.mp4
var FILE = "car-20120827-85.mp4";
var codec = 'video/mp4; codecs="mp4a,avc"';
//var codec = 'video/mp4; codecs="mp4a.40.2,avc1.640028"';
I guess the mime for fMP4 maybe wrong but I can not figure out it after many search from internet.
<!DOCTYPE html>
<html>
<body>
<section>
<video controls autoplay width="320" height="240"></video>
<pre id="log"></pre>
</section>
<script>
//source: http://html5-demos.appspot.com/static/test.webm
//var FILE = "test.webm"
//var codec = 'video/webm; codecs="vorbis,vp8"';
//source http://yt-dash-mse-test.commondatastorage.googleapis.com/media/car-20120827-85.mp4
var FILE = "car-20120827-85.mp4";
var codec = 'video/mp4; codecs="mp4a,avc"';
//var codec = 'video/mp4; codecs="mp4a.40.2,avc1.640028"';
var NUM_CHUNKS = 5;
var video = document.querySelector('video');
window.MediaSource = window.MediaSource || window.WebKitMediaSource;
if (!!!window.MediaSource) {
alert('MediaSource API is not available');
}
var mediaSource = new MediaSource();
video.src = window.URL.createObjectURL(mediaSource);
function callback(e) {
var sourceBuffer = mediaSource.addSourceBuffer(codec);
logger.log('mediaSource readyState: ' + this.readyState);
GET(FILE, function(uInt8Array) {
var file = new Blob([uInt8Array], {type: 'video/webm'});
var chunkSize = Math.ceil(file.size / NUM_CHUNKS);
logger.log('num chunks:' + NUM_CHUNKS);
logger.log('chunkSize:' + chunkSize + ', totalSize:' + file.size);
// Slice the video into NUM_CHUNKS and append each to the media element.
var i = 0;
(function readChunk_(i) {
var reader = new FileReader();
// Reads aren't guaranteed to finish in the same order they're started in,
// so we need to read + append the next chunk after the previous reader
// is done (onload is fired).
reader.onload = function(e) {
sourceBuffer.appendBuffer(new Uint8Array(e.target.result));
logger.log('appending chunk:' + i);
if (i == NUM_CHUNKS - 1) {
mediaSource.endOfStream();
} else {
if (video.paused) {
video.play(); // Start playing after 1st chunk is appended.
}
readChunk_(++i);
}
};
var startByte = chunkSize * i;
var chunk = file.slice(startByte, startByte + chunkSize);
reader.readAsArrayBuffer(chunk);
})(i); // Start the recursive call by self calling.
});
}
mediaSource.addEventListener('sourceopen', callback, false);
mediaSource.addEventListener('webkitsourceopen', callback, false);
mediaSource.addEventListener('webkitsourceended', function(e) {
logger.log('mediaSource readyState: ' + this.readyState);
}, false);
function GET(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200) {
alert("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(new Uint8Array(xhr.response));
};
}
</script>
<script>
function Logger(id) {
this.el = document.getElementById('log');
}
Logger.prototype.log = function(msg) {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(msg));
fragment.appendChild(document.createElement('br'));
this.el.appendChild(fragment);
};
var logger = new Logger('log');
</script>
</body>
</html>
The problem is that fMP4 is a different format than webm. While you can split a webm file in chunks defined arbitrarily, you can't do so with fMP4.
The fMP4 file is just a bunch of "boxes" which are basically structures with a type, length and content (which can contain other boxes, making it hierarchical). You must parse the file and give the sourceBuffer a moov box first (an initialization segment), and then a sequence of moof mdat boxes that can be decoded and played out.
You probably have to read a bit on the fMP4 format (aka ISO BMFF).
String.fromCharCode and String.fromCodePoint both are working fine in chrome developer tools and in the emulator but when i am generating the apk and running it on the actual android device, its not working.
According to MDN's String.fromCodePoint doc:
The String.fromCodePoint method has been added to ECMAScript 2015 and may not be supported in all web browsers or environments yet. Use the code below for a polyfill:
*! http://mths.be/fromcodepoint v0.1.0 by #mathias */
if (!String.fromCodePoint) {
(function() {
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch(error) {}
return result;
}());
var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
var fromCodePoint = function() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) != codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
if (defineProperty) {
defineProperty(String, 'fromCodePoint', {
'value': fromCodePoint,
'configurable': true,
'writable': true
});
} else {
String.fromCodePoint = fromCodePoint;
}
}());
}
so you can try to polyfill String.fromCodePoint in your file
I've just rummaged through and put together an audio-video recorder that will record audio and video streams separately and upload them to my server where they'll get joined.
BUT, my implementation has the audio dropping off after a few seconds mostly 7 seconds and 14 seconds.
I'm using RecordRTC javascript library and here's the link: https://www.webrtc-experiment.com/RecordRTC.js
And here's the code:
var record = document.getElementById('replyfallback_record');
var stop = document.getElementById('replyfallback_cancel');
var audio = document.querySelector('audio');
var recordVideo = document.getElementById('record-video');
var preview = document.getElementById('replyfallback_video');
var recordAudio, recordVideo, progress;
$('#replyfallback_record').click(function(){
switch($('#replyfallback_record').text()){
case "Record":
//setup some variables
var video_constraints = {
mandatory: { },
optional: []
};
//trigger navigator.getUserMedia
navigator.getUserMedia({
audio: true,
video: true
}, function(stream) {
preview.src = window.URL.createObjectURL(stream);
preview.play();
// var legalBufferValues = [256, 512, 1024, 2048, 4096, 8192, 16384];
// sample-rates in at least the range 22050 to 96000.
recordAudio = RecordRTC(stream, {
type: 'audio',
bufferSize: 16384,
sampleRate: 45000
});
/*recordVideo = RecordRTC(stream, {
type: 'video'
});*/
recordAudio.startRecording();
//recordVideo.startRecording();
$('#replyfallback_record').text("Stop & Submit");
});
break;
case "Stop & Submit":
$('#replyfallback_record').attr('disable','disable');
fileName = uid();
recordAudio.stopRecording(function(url){
window.open(url);
});
PostBlob(recordAudio.getBlob(), 'HTML5UploadAudio', fileName);
//recordVideo.stopRecording();
//PostBlob(recordVideo.getBlob(), 'HTML5UploadVideo', fileName);
preview.src = '';
$('#replyfallback_record').text("submitting...");
break;
}
});
//basic ajax request object function
function xhr(url, data, progress, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request.responseText);
}
};
request.onprogress = function(e) {
if(!progress) return;
if (e.lengthComputable) {
progress = (e.loaded / e.total) * 100;
}
$('#replyfallback_record').text("submitting..."+progress);
if(progress == 100){
progress = 0;
}
};
request.open('POST', url);
request.send(data);
}
function PostBlob(blob, fileType, fileName) {
// FormData
var formData = new FormData();
formData.append('filename', fileName);
formData.append('blob', blob);
formData.append("function",fileType);
if(fileType=="HTML5UploadVideo"){
formData.append("CN_UL_title",$('#replyfallback_title').val());
formData.append("CN_UL_description",$('#replyfallback_desc').val());
formData.append("CN_UL_category","1");
}
// POST the Blob
xhr(SITE.api, formData, progress, function(data) {
$('#replyfallback_record').text("Record");
alert(data+" | "+getReadableFileSizeString(recordAudio.getBlob().size));
});
}
It is a little late reply, but may be help future visitor.
Please try PostBlob(recordAudio.getBlob(), 'HTML5UploadAudio', fileName); inside stopRecording callback function.
recordAudio.stopRecording(function(url){
PostBlob(recordAudio.getBlob(), 'HTML5UploadAudio', fileName);
window.open(url);
});
I am getting pretty weird behavior using HTML 5 drag and drop functionality in Safari.
My code looks something like this, nothing fancy:
handleFiles = function (files, e) {
// Traverse throught all files and check if uploaded file type is image
var imageType = /image.*/;
var file = files[0];
// check file type
if (!file.type.match(imageType)) {
alert("File \"" + file.name + "\" is not a valid image file. ");
return false;
}
// check file size
if (parseInt(file.size / 1024) > 2050) {
alert("File \"" + file.name + "\" is too big.");
return false;
}
uploadFile(file);
};
uploadFile = function (file) {
xhr = new XMLHttpRequest();
xhr.open("post", "fileuploadhandler.ext", true);
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
$("#progress").css("width", (event.loaded / event.total) * 100 + "%");
$(".percents").html(" " + ((event.loaded / event.total) * 100).toFixed() + "%");
$(".up-done").html((parseInt(event.loaded / 1024)).toFixed(0));
} else {
alert("Failed to compute file upload length");
}
}, false);
xhr.onreadystatechange = function (oEvent) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
logAction(oEvent);
$("#progress").css("width", "100%");
$(".percents").html("100%");
$(".up-done").html((parseInt(file.size / 1024)).toFixed(0));
fileUploadedComplete(true, oEvent);
} else {
fileUploadedComplete(false, oEvent);
alert("Error" + xhr.statusText);
}
}
};
// Set headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
// Send the file (doh)
xhr.send(file);
};
This works fine in Chrome and Firefox,
Any help would be appreciated!
Best,
tribe84
I can't replicate your error on Safari for OS X.
Perhaps the problem is related to Safari on Windows. Probably, not the best idea to test for Safari on Windows.
Here's a working JSFiddle: http://jsfiddle.net/wh3E5/
I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can't find the way to get a image by web url and then store it in HTML5 file system.
This is my code, but it's wrong.
lib.ajax.get(file , function(xhr, data){
if(xhr.status == 200){
fs.root.getFile("test.jpg", {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
bb.append(data);
fileWriter.write(bb.getBlob('image/jpeg'));
callback && callback("test.jpg");
}, errorHandler);
}, errorHandler);
}
});
The problem is that browser will parse xhr response data as UTF-8,
So the point is to override MimeType:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var xhr = new XMLHttpRequest();
var photoUrl = 'http://localhost:3000/image.jpg';
xhr.open('GET', photoUrl, true);
// This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');
function stringToBinary(response) {
var byteArray = new Uint8Array(response.length);
for (var i = 0; i < response.length; i++) {
byteArray[i] = response.charCodeAt(i) & 0xff;
}
return byteArray
}
function onInitFs(fs) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
fs.root.getFile('image.jpg', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(event) {
$('body').append('<img src="' + fileEntry.toURL() + '"/>');
}
buffer = stringToBinary(xhr.response);
var blob = new Blob([ buffer ], { type: 'image/jpeg' } )
fileWriter.write(blob);
}, errorHandler );
});
}
}
xhr.send();
}
var errorHandler = function(err) {
console.log(err);
}
$(function() {
webkitStorageInfo.requestQuota(PERSISTENT, 5*1024*1024, function(grantedBytes) {
requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler)
}, errorHandler)
})
Here the function I use.
It use Blob constructor so it works on latest Chrome (thats lacks deprecated BlobBuilder) and works also on old iOS 6 that lacks 'blob' for xhr.responseType.
In comments you also see code for the deprecated BlobBuilder.
Notice: you are using XHR so CORS must be enabled!
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);
function onFileSystemSuccess(fileSystem) {
fs = fileSystem;
console.log('File system initialized');
saveAsset('http://www.example-site-with-cors.com/test.png');
}
function saveAsset(url, callback, failCallback) {
var filename = url.substring(url.lastIndexOf('/')+1);
// Set callback when not defined
if (!callback) {
callback = function(cached_url) {
console.log('download ok: ' + cached_url);
};
}
if (!failCallback) {
failCallback = function() {
console.log('download failed');
};
}
// Set lookupTable if not defined
if (!window.lookupTable)
window.lookupTable = {};
// BlobBuilder shim
// var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// xhr.responseType = 'blob';
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) {
// Save this file in the path to URL lookup table.
lookupTable[filename] = fileEntry.toURL();
callback(fileEntry.toURL());
};
writer.onerror = failCallback;
// var bb = new BlobBuilder();
var blob = new Blob([xhr.response], {type: ''});
// bb.append(xhr.response);
writer.write(blob);
// writer.write(bb.getBlob());
}, failCallback);
}, failCallback);
});
xhr.addEventListener('error', failCallback);
xhr.send();
return filename;
}
function fail(evt) {
console.log(evt.target.error.code);
}
On a modern browser supporting XMLHttpRequest Level 2 the method documented in this answer should work.
The relevant standard is explained in this blog post
The trick is to use xhr.responseType = 'blob'
var fs = .... // your fileSystem
function download(fs,url,file,win,fail) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status === 200){
fs.root.getFile(file,{create:true},function(fileEntry){
fileEntry.createWriter(function(writer){
writer.onwriteend = win;
writer.onerror = fail;
writer.write(xhr.response);
})
},fail)
} else {
fail(xhr.status);
}
}
};
xhr.send();
return xhr;
};
Based on cordova-promise-fs (disclosure: I'm the author)
I find a way to do this.
use canvans.toDataURL to transfer data format.
var img = new Image();
var cvs = document.createElement('canvas');
var ctx = cvs.getContext("2d");
img.src = file;
img.onload = function(){
cvs.width = img.width;
cvs.height = img.height;
ctx.drawImage(img, 0, 0);
var imd = cvs.toDataURL(contentType[extname]);
var ui8a = convertDataURIToBinary(imd);
var bb = new BlobBuilder();
bb.append(ui8a.buffer);
fs.root.getFile(path, {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
callback && callback("test.jpg");
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
fileWriter.write(bb.getBlob(contentType[extname]));
});
});
};
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
I get help from here jsfiddle