简体   繁体   中英

PHP and Ajax file upload - Can't get the tmp_name with $_FILES

I'm trying to upload a file using Ajax, but I'm having troubles handling the file... For test purposes I've build a simple code that looks like this:

JS:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST",document.getElementById('upload').action,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var cmdStr="q="+str;
xmlhttp.send(cmdStr);

document.getElementById("ResponseDiv").innerHTML=xmlhttp.responseText;

PHP:

$q=$_POST["q"];
echo $q;

It works fine and xmlhttp.responseText prints [object File] .

My problem, however, is that I need to get the temporary file name with $_FILES["q"]['tmp_name'] . To do so I have changed the code to the following:

JS:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST",document.getElementById('upload').action,true);
xmlhttp.setRequestHeader("enctype","multipart/form-data");
var cmdStr="q="+str;
xmlhttp.send(cmdStr);

document.getElementById("ResponseDiv").innerHTML=xmlhttp.responseText;

PHP:

$q=$_FILES["q"]["tmp_name"];
echo $q;

Problem is that now with xmlhttp.responseText I don't get anything. Anyone knows what I'm doing wrong?

Check out this answer for making file uploads with AJAX. It is possible, but not compatible in all browsers.

jQuery Upload Progress and AJAX file upload

--

Alternatively, if you want on the fly uploads, there is a cool library you can get called 'Uploadify'. It's a flash/jquery (or HTML5 now) rig that allows you to upload files on the fly. In the flash version, last time I used it... you can add in callback functions to make it do essentially anything you want.

Some clever javascript could make this work for you.

http://www.uploadify.com/

AJAX doesn't do file uploads. It's not designed for that. The standard workaround is to have the JS code build a hidden iframe and do a standard POST-type upload in that. As such, if you try doing echo $_FILES['q']['error'] , you'd probably have gotten 4 for "no file".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM