我想仅使用 jQuery 上传单个文件,然后将上传表单替换为处理文件上传的 PHP 脚本的输出。
目前,在我单击提交后,我收到了来自 PHP 脚本的空白响应。我认为这是因为表单数据(文件和上传输入)被上传数据覆盖?
非常感谢任何解决此问题的帮助!
这是我的代码:
HTML
<div id="container">
<form id="form" enctype="multipart/form-data">
<input name="file" type="file">
<input type="hidden" name="upload">
</form>
<a href="javascript:void(0)" onclick="uploadData($('#form').serialize(), 'upload.php', '#container'); return false;">Upload ></a>
</div>
JavaScript
function uploadData(data, url, container) {
var formData = new FormData($(data)[0]);
$.ajax({
type: 'POST',
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
$(container).html(response);
},
error: function() {
alert('Error!');
},
});
return false;
};
PHP
if (isset($_POST['upload'])) {
// check the file has been uploaded
if (isset($_FILES['file'])) {
// check if there was an error uploading the file
if ($_FILES['file']['error'] > 0) {
// display error
echo 'Error: ' . $_FILES['file']['error'];
} else {
// move and store file (overwrite if it already exists)
$fileName = '/upload/' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $fileName);
echo 'File uploaded successfully';
}
} else {
die ('Error: No file selected for upload');
}
}