如何使用Javascript选择文件?

Fra*_*ero 5 html javascript

我正在尝试创建一个Browser Dialog让用户将图像上传到我的网页。

我知道我必须使用 ,<input type="file">但我不知道当用户接受您clickbutton.

就我而言,当您click在 上时button,会出现提示,我通过Javascript.

这是我的代码:

window.onload = function(){ 
  var buttonFile = document.getElementById("buttonFile");
  var file = document.getElementById("file");

  buttonFile.onclick = function(){
    document.getElementById("file").click();
  }

  var files = document.getElementById('file').files[0]; //I do not know where to put this line
  alert(files);
};			
Run Code Online (Sandbox Code Playgroud)
#file{
  display: none;
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" id="file" accept=".jpg, .png, .jpeg">
<button id="buttonFile">Upload file</button>
Run Code Online (Sandbox Code Playgroud)

当然,现在正在检索,undefined因为无论提示是否出现,我都试图检索它。如果我把这条线放在它的onclick事件中,button它也没有信息。我还尝试onclick为该文件创建一个事件,但它也没有检索信息,因为它不知道它何时被接受。

所以在这里我有一些问题:

  • 我应该把这条线放在哪里来获取我上传的图像的值?
  • 由于旧浏览器不支持输入过滤器,我是否也应该在服务器端检查它,对吗?
  • 如果我想在服务器端 ( PHP)检查它,我是否需要将它链接到一个表单?

提前致谢!

A.J*_*.J. 3

到目前为止,一切都正确无误,只是在用户上传文件之前不需要获取文件的值。否则,肯定是未定义的。

window.onload = function() { 
  var buttonFile = document.getElementById("buttonFile");
  var file = document.getElementById("file");

  buttonFile.onclick = function() {
    document.getElementById("file").click();
  };

  file.onchange = function(e){
     if (this.files && this.files[0]) {
        alert(JSON.stringify(this.files[0]));
     }
  };
};
Run Code Online (Sandbox Code Playgroud)

1)您根本不应该将该行放入 onclick 处理程序中。2)你是对的,旧的浏览器不检查类型。无论如何,您应该始终进行服务器端验证。3) 除非您决定使用网络服务。