您需要在服务器上运行的脚本来将文件移动到上载目录。jQuery
ajax方法(在浏览器中运行)将表单数据发送到服务器,然后服务器上的脚本处理上载。这是一个使用PHP的示例。
您的HTML很好,但是将您的JS jQuery脚本更新为如下所示:
$('#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脚本:
<?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); }?>另外,有关目标目录的几件事:
- 确保您具有 正确的服务器路径 ,即,从PHP脚本位置开始,到uploads目录的路径是什么,以及
- 确保它是 可写的 。
还有关于 upload.php
脚本中
move_uploaded_file使用的PHP函数的一些 知识 :
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');
最后,请注意您的PHP
upload_max_filesizeAND
post_max_size配置值,并确保您的测试文件不超过两个。以下是一些帮助您检查PHP配置以及如何设置max filesize和post
settings的帮助。



