I used the code at the link for recording audio and upload to server.
I found some upload progressbar codes but could not merge with this code.
Audio records may be 30-40 mb and upload takes long time.
How can I add upload status for this code below?
https://blog.addpipe.com/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/
var upload = document.createElement('a');
upload.href="#";
upload.innerHTML = "Upload";
upload.addEventListener("click", function(event){
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, filename);
fd.append("filename",blob, 'audiofile');
xhr.open("POST","upload.php",true);
xhr.send(fd);
alert('Uploaded');
}) ```
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(event)
{
var progress = event.loaded / event.total * 100;
console.log('Progress: ' + progress);
});
First here's my client side code:
$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
img.onload = function(){
canvas.width = 600;
canvas.height = 400;
ctx.drawImage(img,0,0,canvas.width,canvas.height);
}
var dataURL = canvas.toDataURL("image/jpg");
var data = new FormData();
data.append("image", dataURL);
var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);
xhttp.send(data);
})
And here's my php code:
$imageArr = explode(',', $_POST['image']);
$image = base64_decode($imageArr[1]);
file_put_contents('image.jpg',$image);
I'm resizing the image on the client side and then sending it as a data url to php to then be saved as an image.
When I save an image it creates a blank image on my server. BUT when I save another image without refreshing the page it saves the previous image in it's place and this time correctly. This is beyond me, can someone please shed some light?
You are sending the image before it is loaded. Your img.onload function is executed after xhttp.send(data). When you upload one more time it gets previous image which is already loaded.
Try following:
$("#fileToUpload").on("change", function(){
var filesToUpload = document.getElementById("fileToUpload");
var file = filesToUpload.files[0];
var img = new Image(600,400);
var reader = new FileReader();
reader.onload = function(e){
img.src = e.target.result;
}
reader.readAsDataURL(file);
var canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 400;
var ctx = canvas.getContext('2d');
img.onload = function(){
ctx.drawImage(img,0,0,canvas.width,canvas.height);
var dataURL = canvas.toDataURL("image/jpg");
var data = new FormData();
data.append("image", dataURL);
var xhttp = new XMLHttpRequest;
xhttp.open("POST", "test.php", true);
xhttp.send(data);
}
})
A possibility to keep in mind: Since everything on client side is setup in the file input's onChange event handler, maybe some setup code is launched in the wrong order and/or not in time to be used as intended? Then, when invoking the onChange event again, resources are already in place /has already been initialized and the image gets displayed as intended.
It's just a theory. To investigate, try to move initializations out of the event handler scope.
I need to provide a means for a user to upload photos to their web site in jpeg format. However, the photos are very large in original size, and I would like to make the resize before upload option very effortless for the user. It seems my only options are a client side application that resizes the photos before uploading them via a web service, or a client side JavaScript hook on the upload operation that resizes the images. The second option is very tentative because I don't have a JavaScript image resizing library, and it will be difficult to get the JavaScript to run my current resize tool, ImageMagick.
I'm sure this is not too uncommon a scenario, and some suggestions or pointers to sites that do this will be appreciated.
In 2011, we can know do it with the File API, and canvas.
This works for now only in firefox and chrome.
Here is an example :
var file = YOUR_FILE,
fileType = file.type,
reader = new FileReader();
reader.onloadend = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
var maxWidth = 960,
maxHeight = 960,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(fileType);
}
}
reader.readAsDataURL(file);
There is multiple-technology-capable Plupload tool which declares that it can do resizing before upload, but I haven't tried it yet. I have also find a suitable answer in my question about binary image handling javascript libs.
You have several options:
Java
ActiveX (only on windows)
Silverlight
Flash
Flex
Google Gears (the most recent version is capable of resizing and drag and drop from your desktop)
I've done a lot of research looking for a similar solution to what you have described and there a lot of solutions out there that vary a lot in quality and flexibility.
My suggestion is find a solution which will do 80% of what you need and customize it to suit your needs.
I think you need Java or ActiveX for that. For example Thin Image Upload
What jao and russau say is true. The reason being is JavaScript does not have access to the local filesystem due to security reasons. If JavaScript could "see" your image files, it could see any file, and that is dangerous.
You need an application-level control to be able to do this, and that means Flash, Java or Active-X.
Unfortunately you won't be able to resize the images in Javascript. It is possible in Silverlight 2 tho.
If you want to buy something already done: Aurigma Image Uploader is pretty impressive - $USD250 for the ActiveX and Java versions. There's some demos on the site, I'm pretty sure facebook use the same control.
Here some modifications to feed tensorflow.js(soo fast with it!!) with resized and cropped image (256x256px), plus showing original image under cropped image, to see what is cut off.
$("#image-selector").change(function(){
var file = $("#image-selector").prop('files')[0];
var maxSize = 256; // well now its minsize
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var canvas2 = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
width *= maxSize / height;
height = maxSize;
}
} else {
if (height > maxSize) {
height *= maxSize / width;
width = maxSize;
}
}
if (width==height) { width = 256; height = 256; }
var posiw = 0;
var posih = 0;
if (width > height) {posiw = (width-height)/2; }
if (height > width) {posih = ((height - width) / 2);}
canvas.width = 256;
canvas.height = 256;
canvas2.width = width;
canvas2.height = height;
console.log('iw:'+image.width+' ih:'+image.height+' w:'+width+' h:'+height+' posiw:'+posiw+' posih:'+posih);
canvas.getContext('2d').drawImage(image, (-1)*posiw, (-1)*posih, width, height);
canvas2.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var dataUrl2 = canvas2.toDataURL('image/jpeg');
if ($("#selected-image").attr("src")) {
$("#imgspeicher").append('<div style="width:100%; border-radius: 5px; background-color: #eee; margin-top:10px;"><div style="position: relative; margin:10px auto;"><img id="selected-image6" src="'+$("#selected-image").attr("src")+'" style="margin: '+document.getElementById('selected-image').style.margin+';position: absolute; z-index: 999;" width="" height=""><img id="selected-image2" src="'+$("#selected-image2").attr("src")+'" style="margin: 10px; opacity: 0.4;"></div><div class="row" style="margin:10px auto; text-align: left;"> <ol>'+$("#prediction-list").html()+'</ol> </div></div>');
}
$("#selected-image").attr("src",dataUrl);
$("#selected-image").width(256);
$("#selected-image").height(256);
$("#selected-image").css('margin-top',posih+10+'px');
$("#selected-image").css('margin-left',posiw+10+'px');
$("#selected-image2").attr("src",dataUrl2);
$("#prediction-list").empty();
console.log("Image was loaded, resized and cropped");
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
let file = $("#image-selector").prop('files')[0];
reader.readAsDataURL(file);});});
Html implementation:
<input id ="image-selector" class="form-control border-0" type="file">
<div style="position: relative; margin:10px auto; width:100%;" id="imgnow">
<img id="selected-image" src="" style="margin: 10px; position: absolute; z-index: 999;">
<img id="selected-image2" src="" style="margin: 10px; opacity: 0.4;">
</div>
Also not resize to a maximum width/height, but to minimum. We get a 256x256px square image.
Pure JavaScript solution. My code resizes JPEG by bilinear interpolation, and it doesn't lose exif.
https://github.com/hMatoba/JavaScript-MinifyJpegAsync
function post(data) {
var req = new XMLHttpRequest();
req.open("POST", "/jpeg", false);
req.setRequestHeader('Content-Type', 'image/jpeg');
req.send(data.buffer);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++){
var reader = new FileReader();
reader.onloadend = function(e){
MinifyJpegAsync.minify(e.target.result, 1280, post);
};
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
You can resize the image in the client-side before uploading it using an image processing framework.
Below I used MarvinJ to create a runnable code based on the example in the following page:
"Processing images in client-side before uploading it to a server"
Basically I use the method Marvin.scale(...) to resize the image. Then, I upload the image as a blob (using the method image.toBlob()). The server answers back providing a URL of the received image.
/***********************************************
* GLOBAL VARS
**********************************************/
var image = new MarvinImage();
/***********************************************
* FILE CHOOSER AND UPLOAD
**********************************************/
$('#fileUpload').change(function (event) {
form = new FormData();
form.append('name', event.target.files[0].name);
reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = function(){
image.load(reader.result, imageLoaded);
};
});
function resizeAndSendToServer(){
$("#divServerResponse").html("uploading...");
$.ajax({
method: 'POST',
url: 'https://www.marvinj.org/backoffice/imageUpload.php',
data: form,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function (resp) {
$("#divServerResponse").html("SERVER RESPONSE (NEW IMAGE):<br/><img src='"+resp+"' style='max-width:400px'></img>");
},
error: function (data) {
console.log("error:"+error);
console.log(data);
},
});
};
/***********************************************
* IMAGE MANIPULATION
**********************************************/
function imageLoaded(){
Marvin.scale(image.clone(), image, 120);
form.append("blob", image.toBlob());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<form id="form" action='/backoffice/imageUpload.php' style='margin:auto;' method='post' enctype='multipart/form-data'>
<input type='file' id='fileUpload' class='upload' name='userfile'/>
</form><br/>
<button type="button" onclick="resizeAndSendToServer()">Resize and Send to Server</button><br/><br/>
<div id="divServerResponse">
</div>
as file_open_contents() is disabled in GAE php.
Any effective way to convert a image file (say png / jpg) and display image in dataurl to hide the filename and path
Let's try this :
HTML :
<input type="file" id="fileToUpload" name="fileToUpload" multiple="multiple">
Javascript :
$("#fileToUpload").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
datasrc = event.target.result;
var inlineImgD = "<img src="+datasrc+">";
};
reader.readAsDataURL(file);
});
});
I have a small problem. i have a link and when i click on this link i want an image to grow to a certain size and move to a certain spot on the screen. Everthing goes fine except that the image pops back to it's original size after the animation is complete.
My project is in Magento so sorry about the weird display of the image
PS: In the img tag it says width="235" height="401".
But the image pops to width=924" and height="1379". These are the dimensions of the actual image.
Here is my HTML code:
<a class="lightbox"href="#">pic</a>
<p class="product-image">
<?php
$_img = '<img id="image1" src="'.$this->helper('catalog/image')->init($_product, 'image').'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" width="235" height="401 " />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
And here is my jQuery code:
(function(window, $, undefined) {
jQuery(function(){
$('.lightbox').click(function(e) {
$('body').css('overflow-y', 'hidden'); // hide scrollbars!
var clicked = $('.lightbox').position();
$('<div id="overlay"></div>')
.css('top', $(document).scrollTop())
.css('opacity', '0')
.animate({'opacity': '0.5'}, 'slow')
.appendTo('body');
$('<div id="lightbox"></div>')
.hide()
.appendTo('body');
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height;
$('<img />')
.attr('src', img.src)
.load(function() {
positionLightboxImage(e, width, height);
})
.click(function() {
removeLightbox();
})
.appendTo('#lightbox');
};
img.src = $('#image1').attr('src');
/*var height = $('<img />').attr('width', .width());
alert(height);
$('<img />')
.attr('src', $(this).attr('href'))
.load(function() {
positionLightboxImage(e);
})
.click(function() {
removeLightbox();
})
.appendTo('#lightbox');
return false;*/
e.preventDefault();
});
});
function positionLightboxImage(e, width, height) {
var top = e.pageY - (height / 2);
var left = e.pageX - (width / 2);
$('#lightbox')
.css({
'top': top,
'left': left
})
.fadeIn(1)
.animate({'width': '50px'}, 3000);
}
function removeLightbox() {
$('#overlay, #lightbox')
.fadeOut('slow', function() {
$(this).remove();
$('body').css('overflow-y', 'auto'); // show scrollbars!
});
}
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
})(window, jQuery);
I hope i gave enough information. :)
For anyone who is interested in this answer.
It isn't the best way to fix this.
But using a smaller image for the lightbox and keeping the big image in the data-src did the trick for this situation.