栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jQuery AJAX文件上传PHP

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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脚本:

<?php    if ( 0 < $_FILES['file']['error'] ) {        echo 'Error: ' . $_FILES['file']['error'] . '<br>';    }    else {        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);    }?>

另外,有关目标目录的几件事:

  1. 确保您具有 正确的服务器路径 ,即,从PHP脚本位置开始,到uploads目录的路径是什么,以及
  2. 确保它是 可写的

还有关于 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_filesize
AND
post_max_size
配置值,并确保您的测试文件不超过两个。以下是一些帮助您检查PHP配置以及如何设置max filesize和post
settings的帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号