我想以尽可能最小的设置在我的 Intranet 页面中实现简单的文件上传。
这是我的 HTML 部分:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
这是我的 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: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
网站根目录下有一个名为“uploads”的文件夹,具有“users”和“IIS_users”的更改权限。
当我选择带有文件表单的文件并按下上传按钮时,第一个警报返回“[object FormData]”。第二个警报没有被调用,并且“uploads”文件夹也为空!?
有人可以帮我找出问题所在吗?
下一步应该是使用服务器端生成的名称重命名该文件。也许有人也可以给我一个解决方案。
最佳答案
您需要一个在服务器上运行的脚本来将文件移动到上传目录。 jQuery ajax
方法(在浏览器中的客户端上运行)将表单数据发送到服务器,然后在服务器上运行的脚本处理上传。
您的 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 脚本位置开始,上传目录的路径是什么,以及
- 确保它可写。
还有一些关于 PHP 函数的信息 move_uploaded_file
,在 upload.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
和 post_max_size
配置值,并确保您的测试文件不超过其中任何一个。这里有一些帮助您 check PHP configuration以及你如何set max filesize and post settings .
关于javascript - jQuery AJAX 文件上传 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681291/