JQuery AJAX 文件上传 PHP

我想实现一个简单的文件上传在我的内部网页,以最小的设置可能。

这是我的 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");
}
});
});

在网站的根目录中有一个名为“上传”的文件夹,具有“用户”和“ IIS _ users”的更改权限。

当我选择一个带有文件表单的文件并按下上传按钮时,第一个警报返回“[ object FormData ]”。第二个警报没有被调用,“上传”文件夹也是空的! ?

有人能帮我找出问题所在吗?

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

484139 次浏览

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

PHP : 一个 PHP 脚本,位于服务器上并运行,将文件导向 upload.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:

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_filesizepost_max_size配置值,并确保您的测试文件不会超过这两个值。这里有一些帮助你如何 检查 PHP 配置和你如何 设置最大文件大小和发布设置

这是接收上传文件的 php 文件

<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();


$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}


echo json_encode($data);
?>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {


},
success: function(data){








},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();


if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}


var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>


**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;


$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);


echo '<img src="'.$location.'" height="100" width="100" />';
}

使用纯 js

async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)

文件名自动包含在请求中,服务器可以读取它,“ content-type”自动设置为“ multipart/form-data”。下面是一个带有错误处理和附加 json 发送的更为成熟的示例

async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
         

formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
    

try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
    

}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>