I want to check the file size of the file selected by user, at the client side by using javascript.The code i am using for this is:
<script type="text/javascript">
var myFile = document.getElementById('myfile');
//binds to onchange event of the input field
myFile.addEventListener('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
</script>
But when i run the code, choose a file, nothing happpens.
Any body tell me what i am doing wrong
Your code works fine (in HTML5 browsers with the File API). Make sure that your <script> block is after the <input> element. In that jsfiddle, it's in the "load" handler.
Works for me using jquery:
http://jsfiddle.net/UUdcy/
$('#myfile').change( function() {
var fileInput = $("#myfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
$('body').append('<p>'+imgbytes+'</p>');
});
You can't get the file size using javascript. Security in the browser prevents file system access by Javascript. You'd need to use Flash, or ActiveX or something that would be able to be granted permissions to do this I believe.
EDIT: If you are using the HTML5 File API then I guess you can do this - but as you've not indicated that anywhere I didn't assume that this was the case. I will put HTML as a tag on your post.
Related
In my current setup I'm uploading a file via a form on "form.php". This form's action calls to a new php file, "upload.php" ,that handles the upload and writes it to the server.
On my form.php I want the user to receive some sort of feedback that the file is being uploaded. This doesn't necessarily have to be a progress bar, a simple percentage from 0-100 will do the trick.
But for some reason all the examples I'm finding via google involve the use of iFrames and I can't get them to work.
Is there a method for only retrieving the percentage uploaded, without the use of iFrames?
So to be clear:
I do want to use jquery/apc/php/ajax etc, whichever require the job to be done.
I don't want to use iFrames/Flash/HTML5 only/Plugins
i have a demo
http://www.longant.com/processbar.php
and you can try!
http://www.longant.com/htmls/342.html
<script src="./jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
total = 100;
intervalId = setInterval(function(){
$.get("/queryTheUploadProcess.php",
function(data){
$(".bar").width(Math.round(data/total*100)+"%");
if (total<data){
clearInterval(intervalId);
}
});
}, 200);
});
</script>
and in queryTheUploadProcess , you can do something what you like !
This is probably a simple question but I am stumped and just don't know where to start.
I have a PHP script (image_feed.php) that returns a URL to an image. Every time this URl is called it returns the latest image available (the image changes every couple of seconds).
What I want to happen is that when the page loads, there is an AJAX call to image_feed.php, which returns the latest url. This URl is then inserted into the HTMl replacing the appropriate image src.
After 5 seconds, I want the process to repeat, and for the image to update. However, I don't want the image to be swapped until it has finished loading, and I want to avoid a white space appearing before the new image loads.
At the moment I have the following jQuery, which simply loads the return value of image_feed.php directly into a div called #image1. image_feed.php is correctly formatted to provide a html image tag.
$(document).ready(function(){
var $container = $("#image1");
$container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>')
var refreshId = setInterval(function()
{
$container.load('image_feed.php?CAMERA_URI=<?=$camera_uri;?>');
}, 5000);
});
This works, but there is a problem. I get a white space the size of the image in IE and Firefox every time the image refreshes, because the image takes a while to download.
I know what I need to is for image_feed.php to return the plain URL to the image. I then use some jQuery to request this URL, pre-load it and then swap it with the existing image.
However, I'm still struggling to get anywhere. Could someone be so kind as to give me some pointers / help?
$(document).ready(function() {
var $img = $('#image1');
setInterval(function() {
$.get('image_feed.php?CAMERA_URI=<?=$camera_uri;?>', function(data) {
var $loader = $(document.createElement('img'));
$loader.one('load', function() {
$img.attr('src', $loader.attr('src'));
});
$loader.attr('src', data);
if($loader.complete) {
$loader.trigger('load');
}
});
}, 5000);
});
Untested. Code above should load the new image in the background and then set the src attribute of the old image on load.
The event handler for load will be executed only once. The .complete check is necessary for browsers that may have cached the image to be loaded. In such cases, these browsers may or may not trigger the load event.
You can. When you want to reload something, you can just append a search query, so that it refreshes the source.
For Eg., when there is a frequently changing image (say captcha) and you wanna load it again, without refreshing the browser, you can do this way:
Initial Code:
<img src="captcha.png" alt="captcha" />
Refreshed Code:
<img src="captcha.png?1" alt="captcha" />
The script used here would be just:
var d = new Date();
$('img').attr('src', $('img').attr('src') + '?_=' + d.getMilliseconds());
Hope this helps! :)
Consider, if you have to fetch the URL again from the server, for a new image URL, you can do this way:
$.ajax({
url: 'getnewimageurl.php',
success: function(data) {
$('img').attr('src', data);
}
});
The server should return only a new image name in it. For eg., the PHP code should be this way:
<?php
$images = array("jifhdfg", "jklduou", "yuerkgh", "uirthjk", "xcjhrii");
die($images[date('u') % count($images)] . ".png"); // Get the random milliseconds mod by length of images.
?>
I suggest you use jQuery 'onImagesLoad' Plugin
This provides you with a callback when an image has finished loading.
When you receive new image URL from server, you create a new <img object with src="new_url_from_server" and attach 'onImagesLoad' callback to it. When your callback is called, your image has finished downloading.
Now you can just replace the 'src' attribute of old img object with new_url_from_server.
Since new image is already avaiable in cache, it will not be downloaded again and will be immediately displayed!
Aletrnatively, you can hide the old image and add this new image to DOM (not required if above works correctly)
Some bare bones sample could be like this:
<!DOCTYPE html>
<html>
<body>
<img id='bla' src="10.jpg" />
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.onImagesLoad.js"></script>
<script type="text/javascript">
$(function(){
var img = $('<div><img src="http://myserverbla/images/verybig.jpg"></img></div>');
img.onImagesLoad({
all : allImgsLoaded
});
function allImgsLoaded($selector){
var allLoaded = ""; //build a string of all items within the selector
$selector.each(function(){
$('#bla').attr('src','http://myserverbla/images/verybig.jpg');
})
}
});
</script>
</body>
</html>
I have a block of php code that loads an image at random. I'm trying to determine when the image has loaded so I can perform some additional actions on it. Here is how I'm currently loading my image:
// Gets my image
$sql = "SELECT id FROM images WHERE user_id=$owner_user_id LIMIT 0,1";
$imgres = mysql_query($sql);
if ($imgres) {
$imgrow = mysql_fetch_array($imgres, MYSQL_ASSOC);
if (!empty($imgrow)) {
echo ('<image src="img.php?id=' . $imgrow['id'] . '" id="profile_img" style="visibility:hidden"/>');
}
}
One of the actions I need to do is get the width of the image. I'm getting the image like so:
alert("IMAGE WIDTH:"+$('#profile_img').width());
It currently returns 0 because it's being called prior to the image being loaded. I've tried adding this method call to my document.ready block but it still gets called prior to the image being loaded. Is there an easy way to determine when the image has loaded?
$(document).ready(function(){
$('#img_id').load(function() {
alert('image is loaded');
});
});
this will do the trick
you can bind a load event handler to your image with jquery:
http://api.jquery.com/load-event/
$("#profile_img").load(function(){
alert(("IMAGE WIDTH:"+$('#profile_img').width())
});
http://api.jquery.com/load-event/
This really has nothing to do with PHP; image loading is done client side, so you'll need to do it in the Javascript side of things. You'll be dealing with Javascript events - here's a primer:
http://www.quirksmode.org/js/introevents.html
Luckily, jQuery has a built-in function to bind to the event for you (even called load()!) which allows you to pass a callback to fire once that content is loaded.
Your best bet is to preload the image in JavaScript prior to the DOM loading at all:
<SCRIPT language="JavaScript">
preload_image = new Image(25,25);
preload_image.src="http://mydomain.com/image.gif";
</SCRIPT>
Do NOT use jQuery .load() to test when images are loaded. According to the jQuery docs:
•It doesn't work consistently nor [is it] reliably cross-browser
•It doesn't fire correctly in WebKit if the image src is set to the same src as before
•It doesn't correctly bubble up the DOM tree
•Can cease to fire for images that already live in the browser's cache
Here is what I am trying to accomplish. I have a form that uses jQuery to make an AJAX call to a PHP file. The PHP file interacts with a database, and then creates the page content to return as the AJAX response; i.e. this page content is written to a new window in the success function for the $.ajax call. As part of the page content returned by the PHP file, I have a straightforward HTML script tag that has a JavaScript file. Specifically:
<script type="text/javascript" src="pageControl.js"></script>
This is not echoed in the php (although I have tried that), it is just html. The pageControl.js is in the same directory as my php file that generates the content.
No matter what I try, I can't seem to get the pageControl.js file included or working in the resulting new window created in response to success in the AJAX call. I end up with errors like "Object expected" or variable not defined, leading me to believe the file is not getting included. If I copy the JavaScript directly into the PHPfile, rather than using the script tag with src, I can get it working.
Is there something I am missing here about scope resolution between calling file, php, and the jQuery AJAX? I am going to want to include javascript files this way in the future and would like to understand what I am doing wrong.
Hello again:
I have worked away at this issue, and still no luck. I am going to try and clarify what I am doing, and maybe that will bring something to mind. I am including some code as requested to help clarify things a bit.
Here is the sequence:
User selects some options, and clicks submit button on form.
The form button click is handled by jQuery code that looks like this:
$(document).ready(function() {
$("#runReport").click(function() {
var report = $("#report").val();
var program = $("#program").val();
var session = $("#session").val();
var students = $("#students").val();
var dataString = 'report=' +report+
'&program=' +program+
'&session=' +session+
'&students=' +students;
$.ajax({
type: "POST",
url: "process_report_request.php",
cache: false,
data: dataString,
success: function(pageContent) {
if (pageContent) {
$("#result_msg").addClass("successMsg")
.text("Report created.");
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
// open a new report window
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// add the report data itself returned from the AJAX call
reportWindow.document.write(pageContent);
reportWindow.document.close();
}
else {
$("#result_msg").addClass("failedMsg")
.text("Report creation failed.");
}
}
}); // end ajax call
// return false from click function to prevent normal submit handling
return false;
}); // end click call
}); // end ready call
This code performs an AJAX call to a PHP file (process_report_request.php) that creates the page content for the new window. This content is taken from a database and HTML. In the PHP file I want to include another javascript file in the head with javascript used in the new window. I am trying to include it as follows
<script src="/folder1/folder2/folder3/pageControl.js" type="text/javascript"></script>
Changed path folder names to protect the innocent :)
The pageControl.js file is actually in the same folder as the jQuery code file and the php file, but I am trying the full path just to be safe. I am also able to access the js file using the URL in the browser, and I can successfully include it in a static html test page using the script src tag.
After the javascript file is included in the php file, I have a call to one of its functions as follows (echo from php):
echo '<script type="text/javascript" language="javascript">writePageControls();</script>';
So, once the php file sends all the page content back to the AJAX call, then the new window is opened, and the returned content is written to it by the jQuery code above.
The writePageControls line is where I get the error "Error: Object expected" when I run the page. However, since the JavaScript works fine in both the static HTML page and when included "inline" in the PHP file, it is leading me to think this is a path issue of some kind.
Again, no matter what I try, my calls to the functions in the pageControls.js file do not work. If I put the contents of the pageControl.js file in the php file between script tags and change nothing else, it works as expected.
Based on what some of you have already said, I am wondering if the path resolution to the newly opened window is not correct. But I don't understand why because I am using the full path. Also to confuse matters even more, my linked stylesheet works just fine from the PHP file.
Apologies for how long this is, but if anyone has the time to look at this further, I would greatly appreciate it. I am stumped. I am a novice when it comes to a lot of this, so if there is just a better way to do this and avoid this problem, I am all ears (or eyes I suppose...)
I have also had problems with a similar issue to this, and this was a real headache. The following approach may not be elegant, but it worked for me.
Make sure that your php file, just outputs what you want in your
body
Add jquery to the window head dynamically
Add any external script files to the window head dynamically
use jQuery html on the window's document to call html() with your loaded content on the body, so that scripts are evaluated.
For example, in your ajax success:
success: function(pageContent) {
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// boilerplate
var boilerplate = "<html><head></head><body></body></html>";
reportWindow.document.write(boilerplate);
var head = reportWindow.document.getElementsByTagName("head")[0];
var jquery = reportWindow.document.createElement("script");
jquery.type = "text/javascript";
jquery.src = "http://code.jquery.com/jquery-1.7.min.js";
head.appendChild(jquery);
var js = reportWindow.document.createElement("script");
js.type = "text/javascript";
js.src = "/folder1/folder2/folder3/pageControl.js";
js.onload= function() {
reportWindow.$("body").html(pageContent);
};
head.appendChild(js);
reportWindow.document.close();
}
Good luck!
It probably isn't looking where you think it is looking to grab your javascript file.
Try a server-relative format like this:
<script src="/some/path/to/pageControl.js"></script>
If that still isn't working, verify that you can type the url to your script file into your browser and get it to download.
Make sure that you have that within either <head> or <body> of the HTML page. Also, I'd double check the path to the .js file. You could do that by pasting "pageControl.js" at the root of your web address.
Things to look for:
Use Firebug (NET tab) to check if the js file is loaded with status 200. Also check in the Console tab for any javascript errors.
Are you using HTML5 offline. If you do, maybe it serves a cached version that doesn't include your <script> tag.
View the page source and make sure it includes the script tag.
Change the source attribute to absolute path: <script src="http://www.example.com/js/pageControl.js" type="text/javascript"></script>
Visit http://www.example.com/js/pageControl.js and make sure it shows correctly.
Try to place the <script> right after the <head> so that it loads first.
This is all I could think of.
You can dynamically load script by creating the element and then append it to head or other element:
reportWindow.document.write(pageContent);
var script = document.createElement('script');
script.src = 'pageControl.js';
script.type = 'text/javascript';
reportWindow.document.getElementsByTagName('head')[0].appendChild(script);
reportWindow.document.close();
Have you tried using the jquery $("#target_div").load(...)
This also executes JS inside the output...
Read this doc to find out how to use it :
http://api.jquery.com/load/
To me it sounds like you're expecting an unloaded script to work.
Try taking a look here: http://ensure.codeplex.com/SourceControl/changeset/view/9070#201379
This is a bit of javascript that ensures that the script is loaded properly before access is attempted. You can use this either as lazy loading (loading javascript files only when required), or, as I interpret your problem, loading a script based on the result of ajax calls.
What's probably happening is, you're echoing a string via an ajax callback, not inserting an element. External scripts require a second GET call to load their contents, which isn't happening - only the first call happened. So, when the first call includes the inline code, the DOM doesn't have to make an additional GET request to fetch the contents. If the DOM doesn't see the script, the DOM won't execute it, which means it's just some random tag.
There's a very fast way to find out. In Chrome (or Firefox with the Firebug plugin installed), check the console > scripts dropdown to see all the loaded scripts. If it's not listed, it's not loaded and the script tag you see in the markup is otherwise inert.
Since it's probably just a string as far as PHP cares, you could create it as PHP DOM object and insert it properly (although this could be laborious). Instead, maybe place it at the very end of the page, just before the closing body tags. (This is the preferred position for js anyway - dead last, after all the other elements on the page have loaded and are available to the DOM.)
HTH :)
I would like to upload files just like google mail does. I would want to use jQuery and PHP to do it is there anyway of getting the progressbar etc.?
Here I added a video of how google does it. http://dl.getdropbox.com/u/5910/Jing/2009-04-02_1948.swf
No flash, no perl or cgi please..
I guess I can live without the progressbar now I am actually searching for information about jquery plugins or just what things I would need to look at
It is weird that people say that gmail doesn't use flash, when you can plainly see the swf file in the gmail interface. Try right clicking on "Attach a file". It is what allows the multiple uploads at once among other things.
The easiest would be to use SWFUpload, it's a small button written in Flash, with all the hooks to drive it in JS. Very easy to use and works well with PHP
but, if you really want it to be pure JS, you'll need some help from the server. specifically, you'll need to start the upload, and periodically query the server about how's it going. unfortunately, PHP upload handling doesn't get any notification until after the download finishes. you'd have to replace it with something else. there are a few pure JS uploaders that include sample Perl server code just because of that.
IOW: JS and PHP don't (fully) cut it. either add flash to the client, or a better upload handler at the server.
in my opinion an excellent article on this topic:
http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html
unfortunately support is lacking for IE and Opera, but hopefully this will change.
Uploadify is another swf (sorry) upload button that uses jquery. Same idea as what Javier mentioned.
PHP doesn't support reporting of upload progress directly. So there is no way of reading the upload status back. However, there is a patch that might work. I haven't tried though.
GMail uses Flash to upload the file in the background. SWFUpload is an open source project that foes something similar.
...gmail uses an iFrame that has style display:hidden; then when you upload on the form, it then sends the iFrame to the upload url. There is no flash involved at all. The only thing Google does with flash on Gmail is just making noises for chats. And you have to allow that in settings. They don't really use flash too much just because it is pretty bad as far as memory and cpu usage. Javascript can do anything flash can do (albiet with a lot more code in some cases) but Javascript, in 99% of cases is much faster, and better memory-wise.
Maybe you could use PlUpload. It has support for a lot of types and is highly customizable. You can check out the demos on the website. On the homepage it also shows what it supports on the homepage and has a fallback mechanism.
http://www.plupload.com/
Edit: It is available as a jQuery plugin.
SWFUpload is gud and compatible with all type of web applications
About Ajax not supporting binary data while form submission.. there is a workaround; if you are jQuery then you can use this Form Plugin (from malsup) here at http://www.malsup.com/jquery/form/. I have been using it for years...
Also plupload seems promising.. thumbs up for that ;) i must say its a bit bulky!!!
In 2018, a website using plain JavaScript can upload files like Google Mail does for mail attachments. A single click can bring up the web browser's file explorer dialog. A separate Submit button is not needed to start the upload. The trick is to use a hidden HTML <input type="file"> element.
Example HTML and JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
<!-- Demo a button to upload files from a local computer to a web server. -->
</head>
<body>
<input type="file" id="inputFileElement" multiple style="display:none">
<button id="fileSelectButton">Select some files</button>
<script>
const fileSelectButton = document.getElementById("fileSelectButton");
const inputFileElement = document.getElementById("inputFileElement");
// When the user presses the upload button, simulate a click on the
// hidden <input type="file"> element so the web browser will show its
// file selection dialog.
fileSelectButton.addEventListener("click", function (e) {
if (inputFileElement) {
inputFileElement.click();
}
}, false);
// When the user selects one or more files on the local host,
// upload each file to the web server.
inputFileElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = inputFileElement.files;
const numFiles = fileList.length;
for (let i = 0; i < numFiles; i++) {
const file = fileList[i];
console.log("Starting to upload " + file.name);
sendFile(file);
}
}
// Asynchronously read and upload a file.
function sendFile(file) {
const uri ="serverUpload.php";
const xhr = new XMLHttpRequest();
const fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log("Finished uploading: " + xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
</script>
</body>
</html>
PHP code:
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
echo $_FILES['myFile']['name'];
exit;
}
?>
This works on Internet Explorer 11, Edge, Firefox, Chrome, Opera.
This example was derived from https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
For a progress bar, see How to get progress from XMLHttpRequest