I'm trying to create a simple binaryStreamReader in javascript. Currently I have the following:
function BinaryStreamReader(file){
var reader = new FileReader();
this.readBytes = function(start, bytes){
reader.readAsBinaryString(file.slice(start,bytes));
reader.onload = function(e){
return e.target.result; //<-- this doesn't work now :P
}
reader.onerror = function(e){
alert("FileError: " + e.target.error.code);
}
}
}
However, I want to use it like this
var bsr = new BinaryStreamReader();
var data = bsr.readBytes(0,128);
Obviously, readBytes() isn't returning anything in my class. Is it possible to let it return whatever onLoad returns?
function BinaryStreamReader(file){
var reader = new FileReader();
this.callback = null;
this.ready = function(callback) {
if(callback) {
this.callback = callback;
}
}
this.readBytes = function(start, bytes){
reader.readAsBinaryString(file.slice(start,bytes));
reader.onload = function(e){
if(this.callback !== null) {
this.callback(e.target.result);
}
}
reader.onerror = function(e){
alert("FileError: " + e.target.error.code);
}
return this;
}
}
var bsr = new BinaryStreamReader();
var data = bsr.readBytes(0,128).ready(function(data) {
alert(data);
});
this should do the trick...
Related
Using the Cordova-file-plugin how do you return the result to a function call.
For example if I call the readFile() like this:
On success I want to return the result back to the function.
<script>
a0 = readFile();
alert(a0);
function readFile(){
alert("Read File");
var type = window.PERSISTENT;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile('log.txt', {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
//var txtArea = document.getElementById('textarea');
//txtArea.value = this.result;
abc = JSON.parse(this.result);
return abc;
// $("body").append(JSON.parse(this.result));
};
reader.readAsText(file);
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("ERROR: " + error.code)
}
};
</script>
I want to ping a few sites using javascript, and found this pen and does what I want.
However, I don't understand when I add goo12121212gle.com to the list of sites as a test it comes up saying that the domain has responded but in the console log I see ERR_NAME_NOT_RESOLVED??
I am new to JS but I am not sure why the below script is both saying the site is there and not at the same time? Is something missing from the script?
function ping(ip, callback) {
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('online');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('offline', e);
}
};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
var PingModel = function (servers) {
var self = this;
var myServers = [];
ko.utils.arrayForEach(servers, function (location) {
myServers.push({
name: location,
status: ko.observable('unchecked')
});
});
self.servers = ko.observableArray(myServers);
ko.utils.arrayForEach(self.servers(), function (s) {
s.status('checking');
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
});
};
var komodel = new PingModel(['goo12121212gle.com','msn.com','104.46.36.174','23.97.201.12']);
ko.applyBindings(komodel);
https://codepen.io/lyellick0506/pen/NGJgry
Both the onerror- and onload-callback use "responded" as the message, so there is no way to differentiate between them:
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e); // <--- change this to a different message
}
};
Alternatively you could just check if the e parameter has been set:
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
My project is about saving the cropped image and show it in the view.
in my form when i cropped the image it works, but when i want to change the image so i crop it again and save. it create two rows with same image.
and when i change the image 3 times it create 3 rows with the same image and so on.
there is method called replace() that i have to use but i dont know how to use it.
this is my code
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('avatar');
var image = document.getElementById('image');
var input = document.getElementById('input');
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
var title = $('#title');
var description = $('#description');
var arabic_title = $('#arabic_title');
var arabic_description = $('#arabic_description');
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
// $alert.hide();
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
console.log('ok2');
};
reader.readAsDataURL(file);
console.log('ok3');
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1.7,
viewMode: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 400,
height: 400,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
document.getElementById('save').addEventListener('click', function () {
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob);
formData.append('title', title.val());
formData.append('description', description.val());
formData.append('arabic_title', arabic_title.val());
formData.append('arabic_description', arabic_description.val());
if (title.val() !== '' && description.val() !== '' && arabic_title.val() !== '' && arabic_description.val() !== '') {
for (let pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax("{{url('admin/services')}}", {
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percent = '0';
var percentage = '0%';
if (e.lengthComputable) {
percent = Math.round((e.loaded / e.total) * 100);
percentage = percent + '%';
$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
}
};
return xhr;
},
success: function (data) {
$alert.show().addClass('alert-success').text('Upload success');
console.log(data);
},
error: function (error) {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
console.log(error);
},
complete: function () {
$progress.hide();
},
});
}
});
});
}
});
});
$service = 'No service';
if (isset($_FILES['img'])) {
$service = Service::create(['title'=>$request->title,
'description'=>$request->description,
'photo'=>$request->img]);
}
return $service;
Try this.
Your Form Should Be
<form action="files/upload" method="post" enctype="multipart/form-data">
<input type="file" name="photo"/>
</form
Your Controller Should Be like
if ($request->hasFile('photo')) {
// move file upload here
}
I have a form with 3 file input fields, but Laravel is giving me this problem: link
So, I will check before sending the files, the maximum resolution will be 2000x2000, I got this code and modified, but it is still giving an error because one passes the other. I want to know how I can unify the 3 checks into one.
Here's my code:
$("#personal").change(function() {
var fr = new FileReader;
fr.onload = function() {
var imgPersonal = new Image;
imgPersonal.onload = function() {
if (imgPersonal.width > 2000 && this.height > 2000) {
$("#submitDocs").attr("disabled", true);
} else {
$("#submitDocs").removeAttr("disabled");
}
};
imgPersonal.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
$("#self").change(function() {
var fr = new FileReader;
fr.onload = function() {
var imgSelf = new Image;
imgPersonal.onload = function() {
if (imgSelf.width > 2000 && this.height > 2000) {
$("#submitDocs").attr("disabled", true);
} else {
$("#submitDocs").removeAttr("disabled");
}
}
};
imgSelf.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
$("#address").change(function() {
var fr = new FileReader;
fr.onload = function() {
var imgAddress = new Image;
imgPersonal.onload = function() {
if (imgAddress.width > 2000 && this.height > 2000) {
$("#submitDocs").attr("disabled", true);
} else {
$("#submitDocs").removeAttr("disabled");
}
}
};
imgAddress.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
Try putting all the duplicate code in a single function, in keeping with DRY, and keeping a persistent object that checks to see if any of the uploaded images are invalid:
const checks = {
personal: true,
self: true,
address: true,
};
function validate(file, checkAttr) {
const fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = function() {
const img = new Image();
img.onload = () => {
if (img.width > 2000 || img.height > 2000) checks[checkAttr] = true;
else checks[checkAttr] = false;
if (checks.personal && checks.self && checks.address) $("#submitDocs").removeAttr("disabled");
else $("#submitDocs").attr("disabled", true);
}
img.src = fr.result;
}
}
$("#personal").change(function() {
validate(this.files[0], 'personal');
});
// other handlers
#CertainPerformance, Thanks, I was able to do it your way, I did this function and I used onblur = "btndisabled();" in each input
function btndisabled() {
var sizePersonal = personal.files[0].size;
var sizeSelf = self.files[0].size;
var sizeAddress = address.files[0].size;
if (sizePersonal < 1000000 && sizeSelf < 1000000 && sizeAddress < 1000000) {
$("#submitDocs").removeAttr("disabled");
} else {
alert('File larger than 1MB');
$("#submitDocs").attr("disabled", true);
}
}
I'm developing HTML5 apps.
When user uploads image from their mobile, the size was too large.
I want to compress the image as PNG like the pngcrush way.
Is there any good way to choice on the frontend (like a javascript library)?
Or is it possible to port the pngcrush library to javascript?
There are a few projects out there which seem to be based around the idea of using emscripten (a LLVM-to-JavaScript compiler) to actually compile the source code from pngcrush to working JavaScript for the browser.
JavaScript-Packer/PNGCrush.html - based on pngcrush-1.7.27
richardassar/pngcrush.js - based on pngcrush-1.7.27
pngcrush-crushed - based on pngcrush-1.7.58
The version for pngcrush-1.7.27 is currently the only one that doesn't seem to produce corrupted images for me. I put together an example which uses promises here: http://plnkr.co/edit/iLpbOjlYiacR04oGdXSI?p=preview
Here's a basic usage example:
var instance = new pngcrush();
instance.exec(inputFile, function (stdoutEvent) {
console.log(stdoutEvent.data.line);
}).then(function (doneEvent) {
var outputFile = new Blob([doneEvent.data.data], { type: 'image/png' });
// do something with the outputFile
});
Here are the contents of the pngcrush-class.js file from the above plunker for reference:
(function(exports) {
var noop = function () {};
function pngcrush () {
this.callbacks = {
'error': [],
'done': [],
'start': [],
'stdout': []
};
}
pngcrush.prototype.exec = function (file, notify) {
var self = this;
if (this.execPromise) {
return this.execPromise.catch(noop).then(function () {
return self.exec(file, notify);
});
}
if (file.type !== 'image/png') {
return Promise.reject(file);
}
var promise = this.execPromise = this.readAsArrayBuffer(file).then(function (event) {
var arrayBuffer = event.target.result;
return self.initWorker().then(function (worker) {
var done = new Promise(function (resolve, reject) {
var offDone, offError, offStdout;
offDone = self.once('done', function (event) {
offError();
offStdout();
resolve(event);
});
offError = self.once('error', function (event) {
offDone();
offStdout();
reject(event);
});
offStdout = self.on('stdout', function (event) {
if (typeof notify === 'function') {
notify.call(self, event);
}
});
worker.postMessage({
'type': 'file',
'data': new Uint8Array(arrayBuffer)
});
worker.postMessage({
'type': 'command',
'command': 'go'
});
});
done.catch(noop).then(function () {
worker.terminate();
});
return done;
});
});
promise.catch(noop).then(function () {
if (promise === self.execPromise) {
delete self.execPromise;
}
});
return promise;
};
pngcrush.prototype.initWorker = function () {
var self = this;
if (this.workerPromise) {
return this.workerPromise;
}
var promise = this.workerPromise = new Promise(function (resolve, reject) {
var worker = new Worker('worker.js');
worker.onerror = function (event) {
var callbacks = [];
reject(event);
Array.prototype.push.apply(callbacks, self.callbacks.error);
while (callbacks.length) {
callbacks.shift().call(self, event);
}
};
worker.onmessage = function (event) {
if (event.data.type === 'ready') {
worker.onmessage = function (event) {
var name = event.data.type;
if (typeof self.callbacks[name] !== 'undefined') {
var callbacks = [];
Array.prototype.push.apply(callbacks, self.callbacks[name]);
while (callbacks.length) {
callbacks.shift().call(self, event);
}
}
};
resolve(worker);
}
};
});
promise.catch(noop).then(function () {
if (promise === self.workerPromise) {
delete self.workerPromise;
}
});
return promise;
};
pngcrush.prototype.on = function (name, callback) {
var self = this;
if (typeof this.callbacks[name] !== 'undefined' && typeof callback === 'function') {
this.callbacks[name].push(callback);
var off = (function () {
var ran = false;
return function () {
if (ran === true) {
return;
}
ran = true;
var idx = self.callbacks[name].lastIndexOf(callback);
if (idx !== -1) {
self.callbacks[name].splice(idx - 1, 1);
}
};
})();
return off;
}
return noop;
};
pngcrush.prototype.once = function (name, callback) {
var off = this.on(name, function () {
off();
callback.apply(this, arguments);
});
return off;
};
pngcrush.prototype.readAsArrayBuffer = function (file) {
var fileReader = new FileReader();
return new Promise(function (resolve, reject) {
fileReader.onerror = reject;
fileReader.onload = resolve;
fileReader.readAsArrayBuffer(file);
});
};
pngcrush.prototype.readAsDataURL = function (file) {
var fileReader = new FileReader();
return new Promise(function (resolve, reject) {
fileReader.onerror = reject;
fileReader.onload = resolve;
fileReader.readAsDataURL(file);
});
};
exports.pngcrush = pngcrush;
})(this);