失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > jquery上传 php jQuery AJAX文件上传PHP

jquery上传 php jQuery AJAX文件上传PHP

时间:2018-08-21 02:58:19

相关推荐

jquery上传 php jQuery AJAX文件上传PHP

小编典典

您需要在服务器上运行的脚本来将文件移动到上载目录。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脚本:

if ( 0 < $_FILES['file']['error'] ) {

echo 'Error: ' . $_FILES['file']['error'] . '

';

}

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'

);

-07-26

如果觉得《jquery上传 php jQuery AJAX文件上传PHP》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。