So I have some form processing code which processes the standard text inputs and also uploaded files (through the $_FILES array)
I want to have the submission done through AJAX
Will jQuery's post(). method still pass that stuff through -> $_FILES or do I need to do something special?
Ajax (as defined, using JavaScript) cannot perform file uploads, as JavaScript cannot access the local filesystem. There are workarounds that seem to use Ajax, such as an iframe or using Flash.
Hunt around Google, you'll find something. There are more libraries (YUI for example) that are putting this together.
To upload files via Ajax, you need to use a workaround using iframes or Flash.
I recommend you Uploadify, it uses flash to do the uploading, and uses jQuery. I like the fact that it has many settings, and it comes with a nice default style for the queue handling. Just follow the instructions to set it up in your site.
In the PHP script you'll receive the file in the $_FILES array, just like if it were a normal submission via a form, the default name is 'Filedata', so you can access your file via $_FILES['Filedata']. Then just echo the response for the Ajax request (JSON or XML), and execute some JS code for the Uploadify 'onComplete' event.
You can try using HTML 5's file upload API, which will require they drag and drop the file into the browser window. Read more here: http://www.appelsiini.net/2009/10/html5-drag-and-drop-multiple-file-upload
Additionally, you can do the same thing with Google Gears (which requires an install for IE but is default on Chrome).
It is possible to detect the presence of either and degrade gracefully.
Related
I am trying to get an image from the user by using file input method. It is successfully getting the image from the user. But I want this input to be passed to my next line of code.
Any help would be appreciated.
<input type='file' name='image'>
$two=createfrompng("Here i want this input to be passed");
You can use $_FILES global variable.
Example :
var_dump($_FILES['image']);
http://php.net/manual/en/reserved.variables.files.php
You can't. Your PHP code is executed server-side. Before the resulting html is send to the client so you don't know if the user WILL upload a file or not and even less it's contents.
The effect you are trying to achieve should be done client-side by altering the DOM with javascript.
But anyway you can't immediately access the image because, for security reasons, javascript can't access client's filesystem so you need to upload the file (the way you are doing) process it server-side and send back to the client, which is difficult if you haven't a websocket connection to start comunication to the client.
I suggest you to slightly change your approach and submit your form targetted to an existing container in your page (tipically a div) and respond with only the html to render the image inside it.
See the jQuery .load() function. It is a simple solution and I think it will be the best for you.
…or another even simpler solution is to reload the whole page and mantain state data server side (if you want to manage multiple images as I thought to understand). It is less responsive. But not to much expensive (if your html is not huge) because the browser cache will remember your images (if you does'nt change the url to download them).
Check first, if the file exists in $_FILES and the use it, in your case:
$image = getimagesize($_FILES['image']['tmp_name']);
if ($image !== false) {
$two = createfrompng($image);
}
I've a form that insert some values using AJAX, and now
I want to add also an image, but I can't get the image
simply using the superglobal $_FILE['file_name'] in the
PHP code, cause the comunication with PHP is under AJAX.
So I'm wondering if I could load the file from the PHP
using the file's path, infact I could simply pass it
throught the JS/AJAX.
Or it's a method that permit me to take the whole file
binary code from the JS/AJAX, then pass it to the PHP
and finallu put it in a BLOB of the SQL db?
Ps.: obviously I must use the ajax
If the file already exists on the server, I think it would be best to just pass the file path to PHP via AJAX and use PHP's file_get_contents function to read it in.
If the file does not exist on the server, you're probably better off submitting a form. PHP executing on the server cannot take a file path and get the file from the client.
If you can use jQuery, you could use an HTML form and capture the submit event, serialize the form into a variable, pass it via AJAX, and return false to prevent the form from submitting (causing a page reload).
EDIT
On second thought, serialize wouldn't be the only part of the solution. That would only get you the value of the file input, not the contents of the file. To get the contents would be much more tedious. It looks like the W3C is working on something, though.
Probably best just to use a standard HTML form.
Currently AJAX does not allow you to upload files.
You just need to use the conventional method.
However, it is a bit possible with Firefox and Chrome. But that method does not work in IE and is rather convoluted.
EDIT
Could consider getting Javascript to use this https://developer.mozilla.org/en-US/docs/DOM/FileReader, serialise it and post that via POST using AJAX. Bit convoluted. FileReader works for Chrome and the latest versions of Firefox. I think it also works for Safari and Opera (but not 100% sure). Probably not for IE.
But it would be a bit complicated at the moment in time to get all browsers to work.
I don't have any expertise regarding uploading files via AJAX. However, if you need help inserting the file into the DB as a BLOB, I can offer some assistance.
Using PDO, it is fairly easy. They have a page dedicated to details regarding LOBs.
$stmt = $db->prepare("INSERT INTO table (image) values (?)");
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $fp, PDO::PARAM_LOB);
$stmt->execute();
How do I start with creating a file upload mechanism that works via Ajax? I've written file upload scripts before but they involved no JavaScript, just submitting a form with a modified encoding type attribute. I need the file upload to have the following features:
Progress bar
Error checking (for network connection drops, bad data, etc)
Absolutely no "manual" form submission, Ajax takes care of it all.
And finally you know those upload buttons that allow you to select multiple files at once compared to the that only lets you select one file at a time? How can I implement those as well?
I'm using PHP as my backend btw.
You can find answers for your questions by looking at already done ajax file uploaders. There are many different plugins for jquery for example. One of the good place to start is to look at elfinder. Its based on jQuery & jQuery UI frontend and has Python and Php connectors for backend.
Here are another usefull links:
jQuery.upload - A simple ajax file upload plugin
Multiple File Upload widget with Drag&Drop support for jQuery
jQuery File Upload Demo
elFinder - file manager for web
The main thing, that you should understand, that its not possible to upload files using xhr-requests. And for today, the only way to upload files, is to use hidden iframes, and some javascript magic to carry out the work.
I've been searching for good file upload scrips for a long time. I've been using the YUI file uploader most recently, but the following should work well with PHP. For some reason I had a heck of a time learning how to get the YUI to work, plus it uses Flash to do the actual upload.
http://aquantum-demo.appspot.com/file-upload
with set up information for PHP on this page:
https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
Alright, so a little preface: I've been working on adding drag and drop file uploading to the course management system called Moodle (specifically 2.0.1). This version of Moodle uses the YUI3 framework and uploads the form data with the file to be uploaded and the save-as name through an io-upload-iframe. The file is stored in the super global $_FILES until the filesystem is sent the relevant data on where to store it permanently.
The trouble I'm having is that instead of using YUI3's drag and drop features (Which, from a cursory look at their website is not the kind of drag and drop I need anyways) I'm using the native HTML5 drag and drop code. This seems to work in most major browsers (I haven't had the time to test much, and it's outside the scope of this project). The trouble I'm having is that this design of DND immediately gives you a file from the Event object in javascript. I could send this file object off to wherever I want, but the filesystem is only designed to handle variables temporarily stored in the $_FILES variable. I've not been able to find any easy way of getting this file stored there, unfortunately. I could to an HTTP request of various forms (either one of YUI3's special Y.io() requests or an XHR), but this requires a lot of duplicated code from the original source code.
Anybody have some suggestions?
Hard to tell what your problem is. But whatever your server or filesystem is, it has nothing to do with the temporarity of the $_FILES array.
When you receive the DND event, and YUI subsequently sends the file, then you will receive some data either in $_FILES or in $_POST. If so, just use move_uploaded_file or file_put_contents and store it elsewhere.
Assign that moved file a md5() hash as name, and have that returned as file identifier for your AJAX-DND upload request.
You can then use that hash id in your Javascript code, and refer to the already uploaded image file by this reference. Should your app initiate a normal form request after the drag'n'dropping, then you just include the collected image reference ids. And thus your server-side code can associate it again.
You could even reconstruct the $_FILES array if you want to:
foreach ((array)$_POST["prev_image_ids"] as $md5) {
$md5 = basename($md5);
$_FILES["image"][] = array(
"tmp_name" => $fn="./already-uploaded/$md5",
"size" => filesize($fn), "type"=>"image/whatever",
"name" => "unknown.jpg", "error"=>UPLOAD_ERR_OK,
); // you could store away those original attributes too
}
Is there a way to construct another element that can enable posting of files to server?
without using the tag
<input type='file'>
If you want to do drag-and-drop, you can use the new drag and drop stuff from HTML5 (supported in Firefox and Chrome as of this writing). That doesn't require an input type='file'.
Otherwise, you cannot do this in pure HTML+JavaScript without an input type='file' element. As thejh points out (in a now-deleted answer), you can do this without actually submitting a form by using the File API, but that still requires using an input type='file' (although it doesn't require submitting a form and refreshing the page). Here's an example (here on SO) of reading a file using JavaScript and the File API; from there, sending it via ajax is a trivial step. And this is useful for providing an enhanced user experience on those browsers that support the File API (progress bars, early detection and reporting of unsupported file types, early detection and reporting of files that are too big, etc.).
You can, of course, do this with non-HTML/JavaScript technologies like Flash and (signed) Java applets, but if you're looking for a "pure" plug-in-free mechanism, the good old input type='file' is still your only bet. You can progressively-enhance it via the File API on browsers that support it, though, which is useful.
You can do it by FLASH, but I don't think there is any other way in html.
Why you don't you want to use input ?
Anyway, check out uploadify (nice jQuery plugin), could be helpful: http://www.uploadify.com/