[英]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: 我正在尝试使用Ajax上传文件,但是在处理文件时遇到了麻烦...为了进行测试,我构建了一个简单的代码,如下所示:
JS: 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: PHP:
$q=$_POST["q"];
echo $q;
It works fine and xmlhttp.responseText
prints [object File]
. 它工作正常,并且
xmlhttp.responseText
打印[object File]
。
My problem, however, is that I need to get the temporary file name with $_FILES["q"]['tmp_name']
. 但是,我的问题是我需要使用
$_FILES["q"]['tmp_name']
获得临时文件名。 To do so I have changed the code to the following: 为此,我将代码更改为以下内容:
JS: 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: PHP:
$q=$_FILES["q"]["tmp_name"];
echo $q;
Problem is that now with xmlhttp.responseText
I don't get anything. 问题是现在使用
xmlhttp.responseText
我什么也没得到。 Anyone knows what I'm doing wrong? 有人知道我在做什么错吗?
Check out this answer for making file uploads with AJAX. 查看此答案以使用AJAX上传文件。 It is possible, but not compatible in all browsers.
可能,但并非在所有浏览器中都兼容。
jQuery Upload Progress and AJAX file upload jQuery上传进度和AJAX文件上传
-- -
Alternatively, if you want on the fly uploads, there is a cool library you can get called 'Uploadify'. 另外,如果您想即时上传,则可以使用一个很酷的库,称为“ Uploadify”。 It's a flash/jquery (or HTML5 now) rig that allows you to upload files on the fly.
这是一个Flash / jquery(或现在的HTML5)绑定,可让您即时上传文件。 In the flash version, last time I used it... you can add in callback functions to make it do essentially anything you want.
在Flash版本中,我上次使用它是...您可以添加回调函数,使其基本上可以执行您想要的任何事情。
Some clever javascript could make this work for you. 一些聪明的javascript可能会为您工作。
AJAX doesn't do file uploads. AJAX不会上传文件。 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.
标准的解决方法是让JS代码构建隐藏的iframe,并在其中执行标准的POST类型的上传。 As such, if you try doing
echo $_FILES['q']['error']
, you'd probably have gotten 4
for "no file". 这样,如果您尝试执行
echo $_FILES['q']['error']
,则“无文件”可能会得到4
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.