发布日期:2018-03-26
jQuery AJAX文件上传php+ 查看更多
jQuery AJAX文件上传php
+ 查看更多
发布日期:2018-03-10 15:50
分类:PHP
浏览次数:199
我想用一个简单的设置在我的内部网页上实现文件上传功能
这是我的HTML部分的代码:
这是我的HTML部分的代码:
这是我的JS jquery脚本:
在网站的根目录中有一个名为"uploads"的文件夹,只有"users"和"IIS_users"拥有更改权限。
当我通过文件夹框选择文件夹,按下上传按钮时,第一个alert函数返回"[object FormData]",第二个alert函数没有被调用,并且"uploads"文件夹也是空的。
当我通过文件夹框选择文件夹,按下上传按钮时,第一个alert函数返回"[object FormData]",第二个alert函数没有被调用,并且"uploads"文件夹也是空的。
有人能帮我找到问题出在哪吗?
另外下一步应该是,用服务器端生成的名称重命名文件。我期望得到一个解决方案。
回答
你需要一个运行在服务器上的能够将文件移动到uploads目录的脚本。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脚本,并将文件定向到uploads目录。
upload.php:在服务器上运行的PHP脚本,并将文件定向到uploads目录。
还有一系列关于目的目录的问题:
1.确保你设置了正确的路径,即从PHP脚本位置开始,上传目录的路径是什么。
2.确保你具有写权限。
还有一点关于PHP函数move_uploaded_file,在upload.php脚本中使用:1.确保你设置了正确的路径,即从PHP脚本位置开始,上传目录的路径是什么。
2.确保你具有写权限。
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和post_max_size的配置值,确保测试文件不超过其中任何一个。 这里有一些关于如何检查PHP配置,如何设置最大文件大小和发布设置的内容。