您需要一个在服务器上运行的脚本来将文件移动到uploads目录.jQuery ajax
方法(在浏览器的客户端上运行)将表单数据发送到服务器,然后服务器上运行的脚本处理上传.
您的HTML没有问题,但请将您的JS jQuery脚本更新为如下所示:
(在// <--
后寻找 comments )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
现在是服务器端脚本,在本例中使用PHP.
upload.php:位于服务器上并在服务器上运行的PHP脚本,将文件定向到uploads目录:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
此外,还有关于目标目录的几件事:
- 确保您有correct server path,即从PHP脚本位置开始上传目录的路径是什么,并且
- 确定是writeable.
还有一点关于upload.php脚本中使用的PHP函数move_uploaded_file
:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name']
是上传时的文件名.你不必用这个.您可以为文件指定任何名称(与服务器文件系统兼容):
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
最后,请注意PHPupload_max_filesize
和post_max_size
配置值,并确保测试文件不超过这两个值.这里有一些帮助,帮助你如何check PHP configuration和如何set max filesize and post settings.