我正在处理 mp3 文件的上传表单,但我碰壁了 :/. 你能帮忙吗?
这是我的 HTML:
<form id="file-form" method="POST">
<input class="profileMenu" id="mp3file" name="mp3file" type="file" multiple/>
</form>
<div onclick="test()" class="col-md-1 profileMenu" id="uploadButton">Upload</div>
这是我的 JavaScript:
function test() {
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('mp3file');
var uploadButton = document.getElementById('uploadButton');
uploadButton.innerHTML = 'Uploading...';
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('mp3file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php/commercial/upload.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}
}
最后是我的 PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['filename']['name']);
if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['filename']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
我正在尝试将 mp3 文件上传到我的服务器并将它们分类到文件夹中,表单验证正常,请求没有返回任何错误,而且似乎我的 php 代码没有做它应该做的事情,我知道我可以做到带有提交按钮而不使用 JavaScript,但我需要这样做。因此,如果你们中的任何人有任何想法,我将非常感激。