如果您只是想让它发挥作用,我推荐 Ravishanker Kusuma'sHayageek jQuery File Upload plugin
. 我通常不推荐插件,但这个插件非常棒。它几乎为您完成所有工作。为什么要重新发明轮子?
http://hayageek.com/docs/jquery-upload-file.php http://hayageek.com/docs/jquery-upload-file.php
他将这个过程分为四个简单的步骤,基本上如下所示:
查找 //1 //2 //3:
<head>
// (1) Load the js files (note that it requires jQuery, which we also load)
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2) Create DIV
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3) initialize plugin
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
最后(第四)步是创建一个 PHP 文件,其名称与上面在 jQuery 代码中指定的名称相同(在本例中my_php_processor.php
) 接收并处理文件:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
注意之间的关系myfile
在 PHP 中($_FILES["myfile"]
) 和文件名myfile
在 jQuery 代码块中指定。
在 Hayageek 网页上,研究upload.php
上的例子Server
tab.
请注意,您还可以将其他变量传递给my_php_processor.php
处理器文件通过使用动态表单数据 http://hayageek.com/docs/jquery-upload-file.php#formdata。请参阅另一个示例:
$("#fileuploader").uploadFile({
url:"my_php_processor.php",
fileName:"myfile",
dynamicFormData: function(){
return {
//my_php_processor.php will receive POST vars below
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
};
},
onSuccess:function(files,data,xhr,pd){
//files: list of files
//data: response from server
//xhr : jquery xhr object
alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
}
});
my_php_processor.php:
<?php
$n = $_POST['newSubj'];
$b = $_POST['newBody'];
$uploadedFile = $_FILES["myfile"]["name"];
//etc.
echo 'This will display in the alert box';
jsFiddle Sample Code http://jsfiddle.net/e18sfhy3/ -
Click on Image Example http://jsfiddle.net/e18sfhy3/1/