我有HTML表单,并希望发送文件myfile的'使用Ajax和jQuery:
I have html form and want send file 'myfile' with Ajax and jQuery:
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="myfile">
</form>
我的JavaScript code:
My javascript code:
function getFile(fieldName){
var itemValue = $('input[name="' + fieldName + '"]')[0].files[0];
return itemValue;
}
function sendFile(){
var formaData = new FormData();
var itemName = 'myfile';
var itemValue = getFile(itemName);
formaData.append(itemName, itemValue);
$.ajax({
type: 'POST',
data: formaData,
processData: false,
contentType: false,
});
}
一切工作正常,当文件被choosen。我在服务器$ _FILES全局数组,并在其中的数据通过Ajax其中有:
All works fine when file is choosen. I have in the server $_FILES global array and data in it which got via Ajax:
["myfile"]=>
array(5) {
["name"]=>
string(13) "file_name.jpg"
["type"]=>
string(10) "image/jpeg"
["tmp_name"]=>
string(14) "/tmp/phpefJlk3"
["error"]=>
int(0)
["size"]=>
int(344100)
}
当文件不choosen的问题! 当我不选择任何文件和发送Ajax请求,然后我有空$ _FILES,但我有$ _ POST与现场MYFILE'等于'不确定'。但我需要在$ _FILES'myfile的'场均是空的。我想是这样的:
The problem when file is not choosen! When I don't choose any file and send Ajax request then I have empty $_FILES, but I have $_POST with field 'myfile' equals 'undefined'. But I need 'myfile' field in $_FILES even it is empty. I want something like:
["myfile"]=>
array(5) {
["name"]=>
string(0) ""
["type"]=>
string(0) ""
["tmp_name"]=>
string(0) ""
["error"]=>
int(4)
["size"]=>
int(0)
}
以上是我在$ _FILES globall数组,如果我把空的形式没有Ajax。我想的一样,如果我使用Ajax。难道posssible?
Above is what I have in $_FILES globall array if I send empty form without Ajax. I want the same if I using Ajax. Is it posssible?
处理文件,AJAX并非如此简单。它配备了大量的因不同的客户端,休文件和所有的东西的问题。你的情况(因为你可以在你的简单误差=这里看到的),没有文件被选中,所以没有必要发送有关不给定文件的信息。不产生费用。也许你看看到控制器。如果数据是不同的(AJAXPOST或POST)以便创建两个PHP-操作。一个AJAX的处理程序和一个后处理程序。在这种情况下,可以处理不同的后DATAS。
Handling files with AJAX is not that simple. It comes up with a lot of problems due to different clients, hugh files and all that stuff. (As you can see in your "simple"-Error here =) In your case, no file is selected so there is no need to send information about "no given file". Dont produce overheads. Maybe you take a look into your controller. If the data is that different (AJAXPOST or POST) so create two PHP-Actions. One AJAX handler and one POST handler. In that case you can handle the different post-datas.
此信息将帮助您: How我可以上传文件异步?
您需要使用像 Uploadify 或的 Valums ,使这项工作。刚刚看了一点关于AJAX和Filepost。
You need to use Plugins like Uploadify, or Valums to make that work. Just read a bit more about AJAX and Filepost.