【发布时间】:2021-03-06 17:58:18
【问题描述】:
我正在测试一些代码,以便能够上传 mp3 文件并将它们存储在网站上。 我已经遵循了一些关于如何使用 JS 和 PHP 执行此操作的教程,但我总是得到错误(在 firefox 中):
XML Parsing Error: no root element found
Location: https://filesavetest.jasperdg.repl.co/ajaxfile.php
Line Number 29, Column 3:
有人可以帮我吗?
这是我的 HTML:
<html>
<head>
<title>JSFileSaveTest</title>
</head>
<body>
<div >
<input type="file" name="file" id="file">
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile();" >
</div>
<script type="text/javascript">
function uploadFile(){
var files = document.getElementById("file").files;
if(files.length>0){
var formdata = new FormData();
formdata.append("file", files[0])
var xhttp = new XMLHttpRequest();
//Set POST method and ajax file path
xhttp.open("POST", "ajaxfile.php", true)
//Call on request changes state
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var response = this.responseText;
if(response==1){
alert("upload suc6")
}else{
alert("file not uploaded")
}
}
}
//Send request with data
xhttp.send(formdata)
}else{
alert("Please select a file")
}
}
</script>
</body>
</html>
这是我的 PHP:
<?php
if(isset($_FILES["file"]["name"])){
//Filename
$filename = $_FILES["file"]["name"];
//Upload location
$dir = "upload/";
//File path
$path = $dir.$filename;
//File extension
$file_extension = pathinfo($path, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
//Valid extensions
$valid_ext = array("mp3");
$response = 0;
//Check extension
if(in_array($file_extension, $valid_ext)){
//Upload file
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path)){
$response=1;
}
}
echo $response;
exit;
}
?>
这是我的文件结构:
[![在此处输入图片描述][1]][1]
Tnx! [1]:https://i.stack.imgur.com/DD3Om.png
【问题讨论】:
标签: javascript php