Filereader and Socket.io uploader: subsequent uploads include previous uploads - javascript

I'm trying to implement a file uploader in html5/js and node that uploads large files in chunks. It works great for a single upload. But when I try and upload again on the same page, it goes into an infinite loop where it looks like it's trying to reupload the previous upload and the new file at once.
Client.js
$('input').change(function() {
var file = this.files[0]
var fileSize = file.size
var fileName = file.name
// file size gate:
var fileSizeLimit = 15000000 // ~15mb
if (fileSize <= fileSizeLimit) {
// get preview blob
var windowURL = window.URL || window.webkitURL
var blobURL = windowURL.createObjectURL(this.files[0])
// render preview image
// render status progress
// set progress to 0
// read the file to server:
var reader = new FileReader()
console.log('new filereader init')
socket.emit('startSend', fileName, fileSize, entryID)
console.log('startSend emitted now for ' + fileName)
reader.onload = function(event) {
var data = event.target.result
console.log('reader onload for ' + fileName)
socket.emit('sendPiece', data, fileName, fileSize, entryID)
}
socket.on('morePlease', function (place, entryID, percent){
progressUpdate(percent)
var chunkSize = 262144
var startPlace = place * chunkSize // The newBlock's Starting Position
var newBlock = file.slice(startPlace, startPlace + Math.min(chunkSize, (fileSize-startPlace)))
reader.readAsBinaryString(newBlock) // triggers reader onload
})
function progressUpdate(percent){
console.log('current percent is: ' + percent + '%')
$('.sendfile .progress').val(percent).text(percent + '%')
}
socket.on('sendSuccessful', function(entryID){
console.log('sendSuccessful triggered for ' + entryID + '. File should be in temp folder.')
$('.status .sendfile').addClass('hidden')
$('.status .savetext').removeClass('hidden')
$('.status .saved').removeClass('hidden')
$('.sendfile .progress').val(0).text('0%')
})
} else {
// file size is too big
}
}) // close input onchange event
Server.js
// start file upload
var chunkSize = 262144
socket.on('startSend', function(fileName, fileSize, entryID) {
var files = {}
console.log('startSend hit for ' + fileName)
files[fileName] = { // create new entry in files {}
fileSize : fileSize,
data : '',
downloaded : 0
}
var fileWriting = files[fileName]
var tempPath = 'temp/' + entryID + '-' + fileName
var place = 0 // stores where in the file we are up to
console.log('place: in startSend, the place for ' + fileName + ' is ' + place) //
try{
var stat = fs.statSync(tempPath)
if(stat.isFile())
{
fileWriting['downloaded'] = stat.size
place = stat.size / chunkSize; // we're passing data in 1/4 mb increments
console.log('downloaded: ' + stat.size)
}
}
catch(er){} // it's a new file
fs.open(tempPath, "a", 0755, function(err, fd){
if(err)
{
console.log(err)
}
else // requesting
{
fileWriting['handler'] = fd //We store the file handler so we can write to it later
var percent = 0
socket.emit('morePlease', place, entryID, percent) // requesting more file pieces
}
})
// processing the file pieces from client
socket.on('sendPiece', function(data, fileName, fileSize, entryID) {
console.log('sendPiece hit for ' + entryID + ' ' + fileName)
fileWriting['downloaded'] += data.length
fileWriting['data'] += data
if(fileWriting['downloaded'] == fileWriting['fileSize']) { // If File is Fully Uploaded
fs.write(fileWriting['handler'], fileWriting['data'], null, 'Binary', function(err, Writen){
console.log('file ' + entryID + 'has been written to temp folder: ' + fileName)
socket.emit('sendSuccessful', entryID)
})
}
else if(fileWriting['data'].length > 10485760){ //If the Data Buffer reaches 10MB
fs.write(fileWriting['handler'], fileWriting['data'], null, 'Binary', function(err, Writen){
fileWriting['data'] = ""; //Reset The Buffer
var place = fileWriting['downloaded'] / chunkSize
var percent = (fileWriting['downloaded'] / fileWriting['fileSize']) * 100
socket.emit('MorePlease', place, entryID, percent) // requesting more file pieces
})
}
else { // need more file pieces
var place = fileWriting['downloaded'] / chunkSize
console.log('MorePlease: ' + fileName + ' pieces needed at place ' + place + ' and percent ' + percent)
var percent = (fileWriting['downloaded'] / fileWriting['fileSize']) * 100
socket.emit('morePlease', place, entryID, percent) // requesting more file pieces
}
})
}) // close startSend
server log: Here's the node log based on the console.logs scattered throughout:
uploading the first file goes fine:
startSend hit for file1.jpeg
place: in startSend, the place for file1.jpeg is 0
sendPiece hit for 52a530f8649b5db8b2000001 file1.jpeg
file 52a530f8649b5db8b2000001has been written to temp folder: file1.jpeg
and for the subsequent file:
startSend hit for file2.JPG
place: in startSend, the place for file2.JPG is 0
sendPiece hit for 52a530f8649b5db8b2000001 file1.jpeg
MorePlease: file1.jpeg pieces needed at place 1.9332275390625 and percent undefined
sendPiece hit for 52a530f8649b5db8b2000001 file1.jpeg
MorePlease: file1.jpeg pieces needed at place 0.96661376953125 and percent undefined
sendPiece hit for 52a530f8649b5db8b2000001 file2.JPG
MorePlease: file2.JPG pieces needed at place 2.6120567321777344 and percent undefined
... infinite loop.
webinspector messages:
reader onload for file1.jpeg (client.js, line 260)
reader onload for file2.JPG (client.js, line 260)
current percent is: 270.227552566774% (client.js, line 273, x2)
current percent is: 242.3942545981759% (client.js, line 273)
InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.
... infinite loop
I've been racking my brain on this for hours , trying to step through the code on my own. I'm not a developer by trade so any help would be super appreciated!

I never use Socket for file uploading with Node.js. Basically, http does an excellent job. This is example code:
var http = require('http'),
fs = require('fs');
var server = http.createServer();
server.listen(8080);
console.log('Start is started on port 8080');
server.on('request', function(req, res) {
var file = fs.createWriteStream('sample.jpg');
var fileSize = req.headers['content-length'];
var uploadedSize = 0;
req.on('data', function (chunk) {
uploadedSize += chunk.length;
var buffer = file.write(chunk);
if(buffer == false)
req.pause();
});
file.on('drain', function() {
req.resume();
});
req.on('end', function() {
res.write('File uploading is completed!!');
res.end();
});
});
If you want to notify the client about progress uploading, you can add some logic in the data event.
By the way, I've found that someone already asked the same question and get the answer. The answer posted a link to a tutorial. I've checked and think that it is a solution that you are looking for. Check this Node.js file upload capabilities: Large Video Files Uploading with support for interruption!

Related

Persist dropzone files in Session storage

I am trying to temporary persist some form data in the session storage and can't find a way to properly store enqueued (not uploaded) dropzone.js files.
Accoring to documentation, I already tried the following:
storing:
dropzone.getQueuedFiles().forEach(function(file, index) {
sessionStorage.setItem("picture_" + index, file.dataURL);
sessionStorage.setItem("picture_" + index + "_name", file.name);
sessionStorage.setItem("picture_" + index + "_type", file.type);
})
retrieving after DOM rendered:
let restoredFiles = 0;
for(let i =0; i < dropzone.options.maxFiles; i++) {
restoredFiles++;
if(sessionStorage.getItem('picture_' + i) !== null){
let data_url = sessionStorage.getItem('picture_' + i);
let name = sessionStorage.getItem('picture_' + i + '_name');
let type = sessionStorage.getItem('picture_' + i + '_type');
let mockFile = {dataURL: data_url, name: name, type: type};
dropzone.emit("addedfile", mockFile);
dropzone.emit("thumbnail", mockFile);
dropzone.createThumbnailFromUrl(mockFile);
dropzone.emit("complete", mockFile);
}
}
dropzone.options.maxFiles = dropzone.options.maxFiles - restoredFiles;
This works fine for adding the file to Dropzone, but there is no way to show a thumbnail. Neither one of the two thumbnail commands acutally produces a thumbnail, and without an actual URL, I can't really use dropzone.createThumbnailFromUrl.
Is there a better way?
It took a good while, but in the end, i solved it like this:
storing:
var images = [];
dropzone.getQueuedFiles().forEach(function (file) {
let image = {
dataURL: file.dataURL,
name: file.name,
type: file.type,
size: file.size,
};
images.push(image);
});
sessionStorage.setItem("images", JSON.stringify(pictures));
retrieving:
var images = JSON.parse(sessionStorage.getItem('images'));
images.forEach(function(image) {
dropzone.files.push(image);
dropzone.emit("addedfile", image);
dropzone.emit("thumbnail", image, image.dataURL);
dropzone.emit("complete", image);
});
dropzone.options.maxFiles = dropzone.options.maxFiles - images.length;

How to detect, that drawing a canvas object is finished?

I have following JS code (found here, on stackoverflow, and a little-bit modded), which resize image on client side using canvas.
function FileListItem(a) {
// Necesary to proper-work of CatchFile function (especially image-resizing).
// Code by Jimmy Wärting (https://github.com/jimmywarting)
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError('expected argument to FileList is File or array of File objects')
for (b = (new ClipboardEvent('')).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
function CatchFile(obj) {
// Based on ResizeImage function.
// Original code by Jimmy Wärting (https://github.com/jimmywarting)
var file = obj.files[0];
// Check that file is image (regex)
var imageReg = /[\/.](gif|jpg|jpeg|tiff|png|bmp)$/i;
if (!file) return
var uploadButtonsDiv = document.getElementById('upload_buttons_area');
// Check, that it is first uploaded file, or not
// If first, draw a div for showing status
var uploadStatusDiv = document.getElementById('upload_status_area');
if (!uploadStatusDiv) {
var uploadStatusDiv = document.createElement('div');
uploadStatusDiv.setAttribute('class', 'upload-status-area');
uploadStatusDiv.setAttribute('id', 'upload_status_area');
uploadButtonsDiv.parentNode.insertBefore(uploadStatusDiv, uploadButtonsDiv.nextSibling);
// Draw sub-div for each input field
var i;
for (i = 0; i < 3; i++) {
var uploadStatus = document.createElement('div');
uploadStatus.setAttribute('class', 'upload-status');
uploadStatus.setAttribute('id', ('upload_status_id_commentfile_set-' + i + '-file'));
uploadStatusDiv.append(uploadStatus);
}
}
var canvasDiv = document.getElementById('canvas-area');
var currField = document.getElementById(obj.id);
var currFieldLabel = document.getElementById(('label_' + obj.id));
// Main image-converting procedure
if (imageReg.test(file.name)) {
file.image().then(img => {
const canvas = document.createElement('canvas')
canvas.setAttribute('id', ('canvas_' + obj.id));
const ctx = canvas.getContext('2d')
const maxWidth = 1600
const maxHeight = 1200
// Calculate new size
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height)
const width = img.width * ratio + .5|0
const height = img.height * ratio + .5|0
// Resize the canvas to the new dimensions
canvas.width = width
canvas.height = height
// Drawing canvas-object is necessary to proper-work
// on mobile browsers.
// In this case, canvas is inserted to hidden div (display: none)
ctx.drawImage(img, 0, 0, width, height)
canvasDiv.appendChild(canvas)
// Get the binary (aka blob)
canvas.toBlob(blob => {
const resizedFile = new File([blob], file.name, file)
const fileList = new FileListItem(resizedFile)
// Temporary remove event listener since
// assigning a new filelist to the input
// will trigger a new change event...
obj.onchange = null
obj.files = fileList
obj.onchange = CatchFile
}, 'image/jpeg', 0.70)
}
)
// If file is image, during conversion show status
function ShowConvertConfirmation() {
if (document.getElementById('canvas_' + obj.id)) {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return true;
}
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return false;
}
}
// Loop ShowConvertConfirmation function untill return true (file is converted)
var convertConfirmationLoop = setInterval(function() {
var isConfirmed = ShowConvertConfirmation();
if (!isConfirmed) {
ShowConvertConfirmation();
}
else {
// Break loop
clearInterval(convertConfirmationLoop);
}
}, 2000); // Check every 2000ms
}
// If file is not an image, show status with filename
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Dodano plik ' + file.name + '</font>';
//uploadStatusDiv.append(uploadStatus);
}
}
Canvas is drawn in hidden div:
<div id="canvas-area" style="overflow: hidden; height: 0;"></div>
I am only detect, that div canvas-area is presented and basing on this, JS append another div with status.
Unfortunatelly on some mobile devices (mid-range smartphones), message will be showed before finish of drawing (it is wrong). Due to this, some uploaded images are corrupted or stay in original size.
How to prevent this?
Everything that should happen after the image has loaded, should be executed within the then callback, or called from within it.
It is important to realise that the code that is not within that callback will execute immediately, well before the drawing has completed.

Photoshop javascript batch replace smart layer from folder and resize

I am trying to work out how to use javascript with photoshop, but eventhough i dont find a logical error in the code, it doesnt work properly.
I have a folder of 1000+ images/.ai files that have varying dimensions. I need these images on the Pillow and saved as .jpeg.
I choose the smartlayer and run the script to choose the images and it saves them correctly. The only problem is, that the resizing of images and positioning dont work properly.
If i put the image in manually, it works without issues, but not with the script.
If the width is greater than the height, it should set the width to 1200 px and calculate the height according to that. (and vice versa) and place in the middle of the layer.
How do i fix the resizing and positioning?
Is it possible to choose a folder where the images are inside instead of selecting the images?
How do i handle it when there are 2 smart layers to change in the mockup instead of 1?
Anyone know where the problem lies this code?
Im grateful for any bit of help!
// Replace SmartObject’s Content and Save as JPG
// 2017, use it at your own risk
// Via #Circle B: https://graphicdesign.stackexchange.com/questions/92796/replacing-a-smart-object-in-bulk-with-photoshops-variable-data-or-scripts/93359
// JPG code from here: https://forums.adobe.com/thread/737789
#target photoshop
if (app.documents.length > 0) {
var myDocument = app.activeDocument;
var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
var thePath = myDocument.path;
var theLayer = myDocument.activeLayer;
// JPG Options;
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 8;
// Check if layer is SmartObject;
if (theLayer.kind != "LayerKind.SMARTOBJECT") {
alert("selected layer is not a smart object")
} else {
// Select Files;
if ($.os.search(/windows/i) != -1) {
var theFiles = File.openDialog("please select files", "*.psd;*.tif;*.jpg;*.ai", true)
} else {
var theFiles = File.openDialog("please select files", getFiles, true)
};
};
(function (){
var startRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var bounds = activeDocument.activeLayer.bounds;
var height = bounds[3].value - bounds[1].value;
var width = bounds[2].value - bounds[0].value;
if (height > width){
var newSize1 = (100 / width) * 800;
activeDocument.activeLayer.resize(newSize1, newSize1, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = startRulerUnits;
}
else{
var newSize2 = (100 / height) * 800;
activeDocument.activeLayer.resize(newSize2, newSize2, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = startRulerUnits;
}
})();
if (theFiles) {
for (var m = 0; m < theFiles.length; m++) {
// Replace SmartObject
theLayer = replaceContents(theFiles[m], theLayer);
var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
// Save JPG
myDocument.saveAs((new File(thePath + "/" + theName + "_" + theNewName + ".jpg")), jpgSaveOptions, true,Extension.LOWERCASE);
}
}
};
// Get PSDs, TIFs and JPGs from files
function getFiles(theFile) {
if (theFile.name.match(/\.(psd|tif|jpg)$/i) != null || theFile.constructor.name == "Folder") {
return true
}
};
// Replace SmartObject Contents
function replaceContents(newFile, theSO) {
app.activeDocument.activeLayer = theSO;
// =======================================================
var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerReplaceContents");
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc3.putPath(idnull, new File(newFile));
var idPgNm = charIDToTypeID("PgNm");
desc3.putInteger(idPgNm, 1);
executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO);
return app.activeDocument.activeLayer
};
I have attached 2 pictures. 1 how it needs to look like and 2 what the script outputs
Correct
Wrong
Your replaced images have to be the same resolution as the smart object.
You can declare the folder path in your code. If you still want to select the path by hand, you can select one image in the path, and extract the parent folder path.
You can recursively go through all of the layers in the documents and extract all the smart objects that you want to replace.
You may want a function to recursively traverse all the layers in the document
function browseLayer(layer, fn) {
if (layer.length) {
for (var i = 0; i < layer.length; ++i) {
browseLayer(layer[i], fn)
}
return;
}
if (layer.layers) {
for (var j = 0; j < layer.layers.length; ++j) {
browseLayer(layer.layers[j], fn);
}
return;
}
//apply this function for every layer
fn(layer)
}
Get all the smart objects in the document
const smartObjects = [];
//The smart objects can be visit twice or more
//use this object to mark the visiting status
const docNameIndex = {};
const doc = app.open(new File("/path/to/psd/file"));
browseLayer(doc.layers, function (layer) {
//You cannot replace smart object with position is locked
if (layer.kind == LayerKind.SMARTOBJECT && layer.positionLocked == false) {
smartLayers.push(layer);
doc.activeLayer = layer;
//open the smart object
executeAction(stringIDToTypeID("placedLayerEditContents"), new ActionDescriptor(), DialogModes.NO);
//activeDocument is now the smart object
const docName = app.activeDocument.name;
if (!docNameIndex[docName]) {
docNameIndex[docName] = true;
smartObjects.push({
id: layer.id,
name: layer.name,
docName: docName,
width : app.activeDocument.width.as('pixels'),
height : app.activeDocument.height.as('pixels'),
resolution : app.activeDocument.resolution //important
});
}
//reactive the main document
app.activeDocument = doc;
}
});
I assume that you have two smart objects needed to replace, the images for replacement are stored in different folders with the same name.
smartObjects[0].replaceFolderPath = "/path/to/folder/1";
smartObjects[1].replaceFolderPath = "/path/to/folder/2";
//we need temp folder to store the resize images
smartObjects[0].tempFolderPath = "/path/to/temp/folder/1";
smartObjects[1].tempFolderPath = "/path/to/temp/folder/2";
Ex: The first iteration will replace smartObjects[0] with "/path/to/folder/1/image1.jpg", and smartObjects[1] with "/path/to/folder/image1.jpg"
Now resize all the images following the properties of the smart objects
smartObjects.forEach(function(smartObject){
//Get all files in the folder
var files = new Folder(smartObject.replaceFolderPath).getFiles();
//Resize all the image files
files.forEach(function (file) {
var doc = app.open(file);
doc.resizeImage(
new UnitValue(smartObject.width + ' pixels'),
new UnitValue(smartObject.height + ' pixels'),
smartObject.resolution
);
//save to temp folder
doc.saveAs(
new File(smartObject.tempFolderPath + "/" + file.name),
new PNGSaveOptions(),
true
);
doc.close(SaveOptions.DONOTSAVECHANGES)
});
});
Finally, replace the smart object
//get list of file again
var files = new Folder(smartObject.replaceFolderPath).getFiles();
files.forEach(function(file){
var fileName = file.name;
smartObjects.forEach(function(smartObject){
//active the window opening the smart object
app.activeDocument = app.documents.getByName(args.documentName);
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), new File(smartObject.tempFolderPath + "/" + fileName));
executeAction(stringIDToTypeID( "placedLayerReplaceContents" ), desc, DialogModes.NO);
});
//Now export document
var webOptions = new ExportOptionsSaveForWeb();
webOptions.format = SaveDocumentType.PNG; // SaveDocumentType.JPEG
webOptions.optimized = true;
webOptions.quality = 100;
doc.exportDocument(new File("/path/to/result/folder" + file.name), ExportType.SAVEFORWEB, webOptions);
});
Now you can close all the opening smart objects
smartObjects.forEach(function (s) {
app.documents.getByName(r.docName).close(SaveOptions.DONOTSAVECHANGES);
});

How to get image width and height using JavaScript before upload?

How to get image width and height using Javascript before upload? I tried to test my code, but it does not work. How can I achieve this?
https://jsfiddle.net/r78qkjba/1/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input name="offer_image_1" onchange="check_thumbnail_image_format_fn()" type="file" id="offer_image_1" />
<script>
function check_thumbnail_image_format_fn() {
var offer_image_1_data = document.getElementById("offer_image_1");
var offer_image_1_data_file = offer_image_1_data.files[0];
var offer_image_1_data_file_width = offer_image_1_data_file.width;
var offer_image_1_data_file_height = offer_image_1_data_file.height;
alert(offer_image_1_data_file_width);
alert(offer_image_1_data_file_height);
};
</script>
HTML5 and the File API
Here's the uncommented working code snippet example:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
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 = file.name +' '+
image.width +'×'+
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file); // Free memory
}
});
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";
}
}
}
if (errors) {
alert(errors);
}
});
#preview img{height:100px;}
<input id="browse" type="file" multiple />
<div id="preview"></div>
Using an input and a div for the images preview area
<input id="browse" type="file" multiple>
<div id="preview"></div>
let's also use a CSS to keep the resulting images a reasonable height:
#preview img{ height:100px; }
JavaScript:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
// 2.
function readImage (file) {
// 2.1
// Create a new FileReader instance
// https://developer.mozilla.org/en/docs/Web/API/FileReader
var reader = new FileReader();
// 2.3
// Once a file is successfully readed:
reader.addEventListener("load", function () {
// At this point `reader.result` contains already the Base64 Data-URL
// and we've could immediately show an image using
// `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
// But we want to get that image's width and height px values!
// Since the File Object does not hold the size of an image
// we need to create a new image and assign it's src, so when
// the image is loaded we can calculate it's width and height:
var image = new Image();
image.addEventListener("load", function () {
// Concatenate our HTML image info
var imageInfo = file.name +' '+ // get the value of `name` from the `file` Obj
image.width +'×'+ // But get the width from our `image`
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
// Finally append our created image and the HTML info string to our `#preview`
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
// If we set the variable `useBlob` to true:
// (Data-URLs can end up being really large
// `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
// Blobs are usually faster and the image src will hold a shorter blob name
// src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
if (useBlob) {
// Free some memory for optimal performance
window.URL.revokeObjectURL(file);
}
});
// 2.2
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
reader.readAsDataURL(file);
}
// 1.
// Once the user selects all the files to upload
// that will trigger a `change` event on the `#browse` input
elBrowse.addEventListener("change", function() {
// Let's store the FileList Array into a variable:
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
var files = this.files;
// Let's create an empty `errors` String to collect eventual errors into:
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for(var i=0; i<files.length; i++) {
// Let's refer to the current File as a `file` variable
// https://developer.mozilla.org/en-US/docs/Web/API/File
var file = files[i];
// Test the `file.name` for a valid image extension:
// (pipe `|` delimit more image extensions)
// The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
// SUCCESS! It's an image!
// Send our image `file` to our `readImage` function!
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
// Notify the user for any errors (i.e: try uploading a .txt file)
if (errors) {
alert(errors);
}
});
Hope below code will help you.
var _URL = window.URL || window.webkitURL;
$("#offer_image_1").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
You don't need to add onchange event at the input node.
This code is taken from
Check image width and height before upload with Javascript

javascript suppress error and continue in for loop

I'm trying to implement a speedtest by downloading 3 image files from the internet, and averaging the time it took to load them. If there is an error for whatever reason, I want to skip loading that image and proceed with the next one. If the error occurs on the last image, then I want to calculate the average speed at that point and return to the caller.
Right now, once an error occurs (I deliberately changed the url of an image so it doesn't exist), it won't go further. I've tried returning true from the .onerror function, but no luck. Any suggestions?
var images = [{
"url": 'http://<removed>250k.jpg?n=' + Math.random(),
"size": 256000
}, {
"url": 'http://<removed>500k.jpg?n=' + Math.random(),
"size": 512000
}, {
"url": '<removed>1000k.jpg?n=' + Math.random(),
"size": 1024000
}
];
function calculateBandwidth() {
var results = [];
for (var i = 0; i < images.length; i++) {
var startTime, endTime;
var downloadSize = images[i].size;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
results.push(speedMbps);
//Calculate the average speed
if (results.length == 3) {
var avg = (parseFloat(results[0]) + parseFloat(results[1]) + parseFloat(results[2])).toFixed(2);
return avg;
}
}
download.onerror = function (e) {
console.log("Failed to load image!");
return true;
};
startTime = (new Date()).getTime();
download.src = images[i].url;
}
}
I think what you're not doing is controlling the process as each event occurs. Each onerror and onload tells you that the process stopped, not that it should quit per se. You initialize one image, it doesn't load, maybe take note, otherwise continue.
The thing is, you do the same thing at the end of onload too. That is, do whatever measurements, then move to the next or, if no more, run the script that cleans up and reports or whatnot.
For instance:
var site = 'http://upload.wikimedia.org/',
imgs = [
'wikipedia/commons/6/6e/Brandenburger_Tor_2004.jpg',
'wikipedia/commons/a/ad/Cegonha_alsaciana.jpg',
'wikipe/Cegonha_alsaciana.jpg',
'wikipedia/commons/d/da/CrayonLogs.jpg',
'wikipedia/commons/1/17/Bobbahn_ep.jpg',
'wikipedia/commons/9/90/DS_Citro%C3%ABn.jpg',
'wikipedia/commons/f/f0/DeutzFahr_Ladewagen_K_7.39.jpg',
'wikipedia/commons/c/c7/DenglerSW-Peach-faced-Lovebird-20051026-1280x960.jpg',
'wikipedia/commons/4/4d/FA-18F_Breaking_SoundBarrier.jpg'
];
My array of images. Hint, wikipe/Cegonha_alsaciana.jpg won't load. Be forewarned, these are large and load slowly and I use a cache buster to keep them firing onloads.
getimg();
In the fiddle, this is all within a window.onload event handler, so when that gets called, this initializes the process. I don't have a setup phase, per se, or otherwise I might have called it init() or setup().
function getimg() {
var img = document.createElement('img'),
path = imgs.shift();
if (path) {
img.onload = loaded;
img.onerror = notloaded;
img.src = site + path + '?cach=bust' + Math.floor(Math.random() * 9999);
console.log('Loading ', img.src);
document.body.appendChild(img);
} else {
console.log('Finished loading images.');
}
function loaded(e) {
console.log('Loaded ', e.target.src);
next();
}
function notloaded(e) {
console.log('Not loaded ', e.target.src);
next();
}
function next() {
console.log(imgs.length, ' imgs left to load.');
getimg();
}
}
http://jsfiddle.net/userdude/vfTfP/
This does what you're trying to do, without the timing mechanism built-in. I can break things off into steps, actions and events, so that I can control the steps as necessary. In a basic way, your script should not run much differently.

Categories

Resources