如何使用javascript访问上传的文件

How to access uploaded file using javascript?

本文关键字:文件 访问 何使用 javascript      更新时间:2023-09-26

我想从js访问csv文件。

所以我使用html中的POST表单标记上传它。

那我怎么能用js访问它呢?

只需简单的ajax请求就可以完成。使用原始java脚本,您可以像这样访问文件。

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var responseText = xhttp.responseText;    //The responseText is the content of your file.
    }
  };
  xhttp.open("GET", "/directory-of-uploaded-files/filename", true);
  xhttp.send();

与jquery

$.ajax({
  url: "/directory-of-uploaded-files/filename",
  method: "get",
  cache: false,
  success: function(file_content){
    console.log(file_content);  //file_content is the content of your file.
  },
  error: function (e) {
    alert("Error");
  }
});

您不能不进行AJAX调用。一旦它在服务器上,客户端将需要请求它

您所要求的是web开发的核心问题,而如何实现这一点在很大程度上取决于您的服务器在运行什么。例如,如果您已经将这个CSV文件发布到运行PHP和MySQL的服务器上,并且它现在存储在MySQL数据库中,则需要服务器端PHP从数据库中检索文件并将其内容提供给客户端。

我希望这能有所帮助。