【问题标题】:"XML Parsing Error: no root element found"“XML 解析错误:找不到根元素”
【发布时间】: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


    【解决方案1】:

    如果服务器不提供 Content-Type 标头,则 XMLHttpRequest 假定 MIME 类型为“text/xml”。您可以通过调用 overrideMimeType() 来指定不同的类型来避免这种情况。

    不确切知道,但在我看来,MP3 的正确 mime 类型是音频/mpeg 或 application/octet-stream。

    尝试在xhttp.open之前设置mimeType,用:

    xhttp.overrideMimeType("audio/mpeg");
    

    或者

    xhttp.overrideMimeType("application/octet-stream");
    

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2021-01-17
      • 2018-06-20
      • 2017-09-08
      相关资源
      最近更新 更多