I have a function that displays a selected image along with the image width and height. I would like to put in a check to alert if the image dimensions are greater that 390x390. I have marked the place I think a size check should go, I may be wrong. But it does not work anyway.
If someone has time you they please take a look to see how I should be dong the size check.
Many thanks in advance for your time.
My script:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
var imageInfo = '<br><br>Your selected file size is<br> Display width ' +
image.width + ', Display height ' +
image.height + ' ' + '';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file);
}
});
reader.readAsDataURL(file);
}
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
// SOMETHING LIKE THIS
if( (image.width < 390 && image.height < 390) .test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Selected image is to small\n";
}
// END
}
}
if (errors) {
alert(errors);
}
});
so you need to move the checking to the event listener because that's the first place where you can know the image resolution
here you don't have the errors list, so you need to modify it a bit yet, but you can start from here:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
if(image.width <= 390 && image.height <= 390)
{
var imageInfo = '<br><br>Your selected file size is<br> Display width ' +
image.width + ', Display height ' +
image.height + ' ' + '';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
} else {
alert ( file.name +" Selected image is to big\n");
}
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file);
}
});
reader.readAsDataURL(file);
}
elPreview.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
for the file variable (on the first place you aimed to check the dimensions, you can only base your condition on the file size - in bytes)
I'm not sure if I understood the question, but did you mean something like this?
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
if(image.width <= 390 && image.height <= 390)
{
readImage( file );
} else {
errors += file.name +" Selected image is to big\n";
}
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
Loading the image and getting the dimension is async, so you can't use the check inside the for loop, it has do be done inside the callback
(unless you are using async/await or generators+yield)
var elBrowse = document.getElementById('image_field')
var elPreview = document.getElementById('preview2')
// No point in addthing the listener if we can't read them anyway
if ('files' in elBrowse) {
// No need for addEventListener if you only going to have 1 listener
elBrowse.onchange = () => {
for (let file of elBrowse.files) {
file.image().then(image => {
// Now if you don't like the extension you can always transform it
// using the canvas element...
if (image.width < 390 && image.height < 390)
return console.error(file.name + ' is to small\n')
let info = `<br><br>${file.name} size is ${file.size} bytes
and dimension is ${image.width}x${image.height}<br>`
elPreview.appendChild(image)
elPreview.insertAdjacentHTML('beforeend', info)
}, err => {
console.error(file.name + " Isn't an image")
})
}
}
} else {
console.info('reading the file is not possible, use flash alternetive?')
}
<!--
Getting a bit of help from Screw-FileReader
ref: https://github.com/jimmywarting/Screw-FileReader
-->
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>
<!--
use the accept attribute to say that you only want images
So you don't have to check for it in your code
But for just in case we listen for image.onerror when we load the image
-->
<input id=image_field type=file multiple accept="image/*">
<div id=preview2>
Related
I'm new to Dropzone Js and i want to upload a file, process data to json then upload to my Flask server.
i appreciate any kind of help, thanks.
var id = '#kt_dropzone_4';
// set the preview element template
var previewNode = $(id + " .dropzone-item");
previewNode.id = "";
var previewTemplate = previewNode.parent('.dropzone-items').html();
previewNode.remove();
var myDropzone4 = new Dropzone(id, { // Make the whole body a dropzone
url: "/Upload", // Set the url for your upload script location
headers: {
'x-csrftoken': $('#csrf_Upload').val()
},
method: "post",
parallelUploads: 5,
acceptedFiles: ".xls, .xlsx, .csv",
previewTemplate: previewTemplate,
maxFilesize: 2, // Max filesize in MB
autoQueue: false, // Make sure the files aren't queued until manually added
previewsContainer: id + " .dropzone-items", // Define the container to display the previews
clickable: id +
" .dropzone-select" // Define the element that should be used as click trigger to select files.
});
myDropzone4.on("addedfile", function (file) {
// Hookup the start button
file.previewElement.querySelector(id + " .dropzone-start").onclick = function () {
myDropzone4.enqueueFile(file);
};
$(document).find(id + ' .dropzone-item').css('display', '');
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'inline-block');
//remove duplicates
if (this.files.length) {
var i, len;
for (i = 0, len = this.files.length; i < len - 1; i++) // -1 to exclude current file
{
if (this.files[i].name === file.name && this.files[i].size === file.size && this.files[i]
.lastModifiedDate.toString() === file.lastModifiedDate.toString()) {
this.removeFile(file);
$('#muted-span').text('Duplicates are not allowed').attr('class', 'kt-font-danger kt-font-bold').hide()
.fadeIn(1000)
setTimeout(function () {
$('#muted-span').hide().text('Only Excel and csv files are allowed for upload')
.removeClass('kt-font-danger kt-font-bold').fadeIn(500);
}, 2500);
}
}
}
});
// Update the total progress bar
myDropzone4.on("totaluploadprogress", function (progress) {
$(this).find(id + " .progress-bar").css('width', progress + "%");
});
myDropzone4.on("sending", function (file, response) {
console.log(file)
console.log(response)
// Show the total progress bar when upload starts
$(id + " .progress-bar").css('opacity', '1');
// And disable the start button
file.previewElement.querySelector(id + " .dropzone-start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone4.on("complete", function (progress) {
var thisProgressBar = id + " .dz-complete";
setTimeout(function () {
$(thisProgressBar + " .progress-bar, " + thisProgressBar + " .progress, " + thisProgressBar +
" .dropzone-start").css('opacity', '0');
}, 300)
});
// Setup the buttons for all transfers
document.querySelector(id + " .dropzone-upload").onclick = function () {
myDropzone4.enqueueFiles(myDropzone4.getFilesWithStatus(Dropzone.ADDED));
};
// Setup the button for remove all files
document.querySelector(id + " .dropzone-remove-all").onclick = function () {
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'none');
myDropzone4.removeAllFiles(true);
};
// On all files completed upload
myDropzone4.on("queuecomplete", function (progress) {
$(id + " .dropzone-upload").css('display', 'none');
});
// On all files removed
myDropzone4.on("removedfile", function (file) {
if (myDropzone4.files.length < 1) {
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'none');
}
});
I have not found yet a way to get the uploaded data from dropzonejs. I tried to read the file with FileReader but it's not a binary data (correct me if i'm wrong).
I need to process data on myDropzone4.on("addedfile", function (file){})
and return it as a json format if possible.
I found an answer for it, I just needed to find the input type file.when using dropzone.js either you find the input type file in the html page or in their javascript file, where i found that the input type file was being created with a class to hide this element :
var setupHiddenFileInput = function setupHiddenFileInput() {
if (_this3.hiddenFileInput) {
_this3.hiddenFileInput.parentNode.removeChild(_this3.hiddenFileInput);
}
_this3.hiddenFileInput = document.createElement("input");
_this3.hiddenFileInput.setAttribute("type", "file");
_this3.hiddenFileInput.setAttribute("id", "123");
if (_this3.options.maxFiles === null || _this3.options.maxFiles > 1) {
_this3.hiddenFileInput.setAttribute("multiple", "multiple");
}
// _this3.hiddenFileInput.className = "dz-hidden-input";
}
so i gave it an id and bind an event to the input then i read the file with two functions depends on the format of the file uploaded, for csv files to json :
function getText(fileToRead) {
var reader = new FileReader();
reader.readAsText(fileToRead);
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
process(csv);
}
function process(csv) {
// Newline split
var lines = csv.split("\n");
result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length - 1; i++) {
var obj = {};
//Comma split
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
console.log(result);
}
function errorHandler(evt) {
if (evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
Read excel files (xls,xlsx) format to json format:
var ExcelToJSON = function () {
this.parseExcel = function (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function (sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[
sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.onerror = function (ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
the event that will detect change on the input, detect file format then use one of those to get the result in a JSON format:
$(document).ready(function () {
$('input[type="file"]').on('change', function (e) {
// EXCEL TO JSON
var files = e.target.files;
console.log(files)
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
var fileName = e.target.files[0].name;
console.log('The file "' + fileName + '" has been selected.');
// CSV TO JSON
var files = e.target.files;
if (window.FileReader) {
getText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
});
});
I hope this helps i'm using dropzonejs with keenthemes implementation.
I have these codes to display the names of the files selected from input and it will preview the FIRST image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var filename = input.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#my_file')[0].files;
for (var i = 0; i < files.length; i++) {
$("#files").append('<div class="filename"><span name="fileNameList">'+files[i].name+'</span></div>');
}
$("#nextBtn").on("click",function(){
})
$('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
What i want to do is that when i click on the "next" button,it will go to the next image selected or if i click on the "prev" button,it will go to the previous image(the last image if im displaying the first one).How do i go about doing this?Thank You.
UPDATE:
var fileInput = document.getElementById("my_file");
$(fileInput).on("change",function(event){
var next = document.getElementById("nextBtn");
next.onclick = function(xFlip){
curImage = curImage+xFlip;
var files = event.target.files;
if(curImage > files.length){
curImage = 1;
}
if(curImage == 0){
curImage = files.length;
}
$("#myImg").attr('src',files[curImage-1]);
};
console.log(document.getElementById("myImg").getAttribute("src"));
});
I did it this way as the images are retrieved from input type file multiple.
https://jsfiddle.net/bfr6wp7e/2/
Thanks for the challenge, it was my first meeting with the File API :)
Here is the jsFiddle with what I believe is the correct answer to your question:
https://jsfiddle.net/mkbctrll/aq9Laaew/300936/
JS part
const fileInupt = document.getElementById('fileInput')
const fileList = document.getElementById('fileList')
const slickSettings = {
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true
}
const initSlickCarousel = (target, settings) => {
$(target).slick(settings);
}
const handleInputChange = (event) => {
console.log('We are handling it sir!')
const filesArray = Array.from(event.target.files)
filesArray.map((singleFile) => {
const outputImg = document.createElement('img')
const fileReader = new FileReader()
outputImg.className = 'img-thumbnail'
// Let's read it as data url - onload won't return a thing without it
fileReader.readAsDataURL(singleFile)
fileReader.onload = (event) => { outputImg.src = event.target.result }
console.log(outputImg)
fileList.appendChild(outputImg)
})
initSlickCarousel(fileList, slickSettings)
}
if(window.File && window.FileReader && window.FileList) { // check if browser can handle this
console.log('We are good to go sir!')
fileInput.addEventListener('change', handleInputChange, false)
} else {
alert('File features are not fully supported. Please consider changing the browser (newest Chrome or Mozilla).')
}
Though it won't be possible for me to get a grasp on that tech if not for the following sources:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload
Sample code for Prev and Next image slide.
var numImages = 4;
var curImage = 1;
var imgArray =[
"one.jpg",
"two.jpg",
"three.jpg",
"four.jpg"
];
function imageShow( xflip ) {
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document.images[2].src = imgArray[curImage - 1];
}
HTML buttons:
<input type="button" value="<< Prev" onclick="imageShow(-1)">
<input type="button" value="Next >>" onclick="imageShow(1)">
I am trying to capture images using cordovaCamera and imagePicker then remove the EXIF data and create a copy of the image that I get after the metadata is removed.
In the following code I get image file in Blob format which I pass to resolveLocalFileSystemURL but unable to proceed as resolveLocalFileSystemURL does not accept blob or base64 data so is it possible to convert Blob/Base64 to fileURI format. Or is there any alternative to solve this.
In html:
<input id="erd" type="file"/>
In controllers.js :
var input = document.querySelector('#erd');
input.addEventListener('change', load);
function load(){
var fr = new FileReader();
fr.onload = process;
fr.readAsArrayBuffer(this.files[0]);
console.log(" onload "+URL.createObjectURL(this.files[0]));
}
function process(){
var dv = new DataView(this.result);
var offset = 0, recess = 0;
var pieces = [];
var i = 0;
if (dv.getUint16(offset) == 0xffd8){
offset += 2;
var app1 = dv.getUint16(offset);
offset += 2;
while (offset < dv.byteLength){
if (app1 == 0xffe1){
pieces[i] = {recess:recess,offset:offset-2};
recess = offset + dv.getUint16(offset);
i++;
}
else if (app1 == 0xffda){
break;
}
offset += dv.getUint16(offset);
var app1 = dv.getUint16(offset);
offset += 2;
}
if (pieces.length > 0){
var newPieces = [];
pieces.forEach(function(v){
newPieces.push(this.result.slice(v.recess, v.offset));
}, this);
newPieces.push(this.result.slice(recess));
var br = new Blob(newPieces, {type: 'image/jpeg'});
console.log(" pieces.length "+URL.createObjectURL(br));
$scope.strimg=URL.createObjectURL(br).toString();
//var file = new File(URL.createObjectURL(br), "uploaded_file.jpg", { type: "image/jpeg", lastModified: Date.now() });
var myFile = blobToFile(br, "my-image.jpg");
console.log('myFile'+JSON.stringify(myFile));
$scope.strimg = myFile;
createFileEntry($scope.strimg);
}
}
}
function blobToFile(theBlob,fileName){
console.log('theBlob'+theBlob+fileName);
var b = theBlob;
b.lastModifiedDate = new Date();
b.name = fileName; //Cast to a File() type
return theBlob;
}
function createFileEntry(fileURI) {
window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
}
// 5
function copyFile(fileEntry) {
console.log(" copyFile "+fileEntry);
var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('/') + 1);
var newName = name;
$scope.filepathnew="file:///storage/emulated/0/Android/data/com.offermanagement.system/files/";
window.resolveLocalFileSystemURL($scope.filepathnew, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
newName,
onCopySuccess,
fail
);
},
fail);
}
function onCopySuccess(entry) {
$scope.$apply(function () {
$rootScope.profilepic=entry.nativeURL;
$rootScope.images.push(entry.nativeURL);
$rootScope.items.push({src:entry.nativeURL,sub:'' });
});
}
function fail(error) {
console.log("fail: " + error.code);
}
I get the following error for the above code
"Uncaught TypeError: Wrong type for parameter "uri" of resolveLocalFileSystemURI: Expected String, but got Blob."
I want to build a voice recorder using HTML5 same as one found in gitHub JSSoundecorder, but what I want is for the user to be able to choose the file format before recording the voice.I can do this using ffmpeg. In other words the user must be able to select the audio format by check box (mp3,wma,pcm) and in the background code, the .wav file usually created by the program instead of displaying it, it should be converted by the format selected then displayed in the new format.this is the ffmpeg code we can use ,but I don't know how to get the .wav audio file to convert it and show it.please if someone have ideas,or if can find demos I have been looking for weeks.this is the ffmpeg code:
var fileName;
var fileBuffer;
function timeToSeconds(time) {
var parts = time.split(":");
return parseFloat(parts[0]) * 60 * 60 + parseFloat(parts[1]) * 60 + parseFloat(parts[2]) + parseFloat("0." + parts[3]);
}
// create ffmpeg worker
function getFFMPEGWorker() {
// regexps for extracting time from ffmpeg logs
var durationRegexp = /Duration: (.*?), /
var timeRegexp = /time=(.*?) /;
var duration;
var ffmpegWorker = new Worker('worker.js');
var durationLine;
ffmpegWorker.addEventListener('message', function(event) {
var message = event.data;
console.log(message.type);
if (message.type === "ready" && window.File && window.FileList && window.FileReader) {
// script loaded, hide loader
$('#loading').hide();
} else if (message.type == "stdout") {
console.log(message.data);
} else if (message.type == "stderr") {
console.log(message.data);
// try to extract duration
if (durationRegexp.exec(message.data)) {
duration = timeToSeconds(durationRegexp.exec(message.data)[1]);
}
// try to extract time
if (timeRegexp.exec(message.data)) {
var time = timeToSeconds(timeRegexp.exec(message.data)[1]);
if (duration) {
$("#progress").text("Progress: " + Math.floor(time / duration * 100) + "%");
$("#progress").show();
}
}
} else if (message.type == "done") {
var code = message.data.code;
console.log(message.data);
var outFileNames = Object.keys(message.data.outputFiles);
console.log(outFileNames);
if (code == 0 && outFileNames.length) {
var outFileName = outFileNames[0];
var outFileBuffer = message.data.outputFiles[outFileName];
var src = window.URL.createObjectURL(new Blob([outFileBuffer]));
$("#downloadLink").attr('href', src);
$("#download").show();
} else {
$("#error").show();
}
$("#converting").hide();
$("#progress").hide();
}
}, false);
return ffmpegWorker;
}
// create ffmpeg worker
var ffmpegWorker = getFFMPEGWorker();
var ffmpegRunning = false;
$('#convert').click(function() {
// terminate existing worker
if (ffmpegRunning) {
ffmpegWorker.terminate();
ffmpegWorker = getFFMPEGWorker();
}
ffmpegRunning = true;
// display converting animation
$("#converting").show();
$("#error").hide();
// hide download div
$("#download").hide();
// change download file name
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
var outFileName = fileName.substr(0, fileName.lastIndexOf('.')) + "." + getOutFormat();
$("#downloadLink").attr("download", outFileName);
$("#downloadLink").text(outFileName);
var arguments = [];
arguments.push("-i");
arguments.push(fileName);
arguments.push("-b:a");
arguments.push(getBitrate());
switch (getOutFormat()) {
case "mp3":
arguments.push("-acodec");
arguments.push("libmp3lame");
arguments.push("out.mp3");
break;
case "wma":
arguments.push("-acodec");
arguments.push("wmav1");
arguments.push("out.asf");
break;
case "pcm":
arguments.push("-f");
arguments.push("s16le");
arguments.push("-acodec");
arguments.push("pcm_s16le");
arguments.push("out.pcm");
}
ffmpegWorker.postMessage({
type: "command",
arguments: arguments,
files: [
{
"name": fileName,
"buffer": fileBuffer
}
]
});
});
function getOutFormat() {
return $('input[name=format]:checked').val();
}
function getBitrate() {
return $('input[name=bitrate]:checked').val();
}
// disable conversion at start
$('#convert').attr('disabled', 'true');
function readInputFile(file) {
// disable conversion for the time of file loading
$('#convert').attr('disabled', 'true');
// load file content
var reader = new FileReader();
reader.onload = function(e) {
$('#convert').removeAttr('disabled');
fileName = file.name;
console.log(fileName);
fileBuffer = e.target.result;
}
reader.readAsArrayBuffer(file);
}
// reset file selector at start
function resetInputFile() {
$("#inFile").wrap('<form>').closest('form').get(0).reset();
$("#inFile").unwrap();
}
resetInputFile();
function handleFileSelect(event) {
var files = event.target.files; // FileList object
console.log(files);
// files is a FileList of File objects. display first file name
file = files[0];
console.log(file);
if (file) {
$("#drop").text("Drop file here");
readInputFile(file);
}
}
// setup input file listeners
document.getElementById('inFile').addEventListener('change', handleFileSelect, false);
In Firefox 3 it is possible to access the contents of a <input type="file"> element as in the following.
Assume a form with the following element:
<input type="file" id="myinput">
Now the data of the file selected can be accessed with:
// Get the file's data as a data: URL
document.getElementById('myinput').files[0].getAsDataURL()
Is there a cross-browser way to accomplish the same thing?
Firefox documentation for this feature:
https://developer.mozilla.org/en/nsIDOMFileList
https://developer.mozilla.org/en/nsIDOMFile
This is possible in at least Chrome, Firefox and Safari: Reading Files.
see associated jsfiddle
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = _.reduce(evt.target.result,
function(sum, byte) {
return sum + ' 0x' + String(byte).charCodeAt(0).toString(16);
}, '');
document.getElementById('byte_range').textContent =
['Read bytes: ', start + 1, ' - ', stop + 1,
' of ', file.size, ' byte file'].join('');
}
};
var blob;
if (file.slice) {
blob = file.slice(start, stop + 1);
}else if (file.webkitSlice) {
blob = file.webkitSlice(start, stop + 1);
} else if (file.mozSlice) {
blob = file.mozSlice(start, stop + 1);
}
console.log('reader: ', reader);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);