gpt4 book ai didi

javascript - jQuery AJAX 文件上传 PHP

转载 作者:IT老高 更新时间:2023-10-28 11:44:52 26 4
gpt4 key购买 nike

我想在我的 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]”。第二个警报没有被调用,并且“上传”文件夹也是空的!?

谁能帮我找出问题所在?

下一步应该是用服务器端生成的名称重命名文件。也许有人也可以给我一个解决方案。

最佳答案

您需要在服务器上运行的脚本将文件移动到上传目录。 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']);
}

?>

另外,关于目标目录的一些事情:

  1. 确保您拥有正确的服务器路径,即从 PHP 脚本位置开始,上传目录的路径是什么,并且
  2. 确保它是可写的

还有一点关于 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/23980733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com