首页 > javascript > file.files [0]无法读取未定义的属性“0”

file.files [0]无法读取未定义的属性“0” (file.files[0] cannot read property '0' of undefined)

问题

奇怪的是,如果我在jsfiddle中使用此代码,它可以很好地工作

var file = document.getElementById("file");
function CallAlert(){
	alert(file.files[0].name);
}
<form method="post" enctype="multipart/form-data">
 <div>
   <label for="file">Choose file to upload</label>
   <input type="file" id="file" name="file" onchange="CallAlert()">
 </div>
 <div>
   <button>Submit</button>
 </div>
</form>


结果是带有文件名的警报

现在我的问题在我的情况下使用相同的方法返回 Uncaught TypeError: Cannot read property '0' of undefined

function _(el) {
  return document.getElementById(el);
}

function uploadFile() {
  var file = _('file1').files[0];
  if (typeof file === 'undefined') {
    _('status').innerHTML = 'ERROR: Please browse for a file before clicking the upload button';
    _('progressBar').value = 0;
  } else {
    $.get('https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php?getsize', function(sizelimit) {
      if (sizelimit > file.size) {
        var formdata = new FormData();
        formdata.append('file1', file);
        formdata.append('size', file.size);
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener('progress', progressHandler, false);
        ajax.addEventListener('load', completeHandler, false);
        ajax.addEventListener('error', errorHandler, false);
        ajax.addEventListener('abort', abortHandler, false);
        ajax.open('POST', 'https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php');
        ajax.send(formdata);
      } else {
        var sizewarn = 'ERROR: The File is too big! The maximum file size is ';
        sizewarn += sizelimit / (1024 * 1024);
        sizewarn += 'MB';
        _('status').innerHTML = sizewarn;
        _('progressBar').value = 0;

      }
    });
  }
}

function progressHandler(event) {
  // _('loaded_n_total_bytes').innerHTML = event.loaded+'bytes/''+event.total+'bytes';
  // _('loaded_n_total_kb').innerHTML = event.loaded/1024+'kb/''+event.total/1024+'kb';
  _('loaded_n_total_mb').innerHTML = Math.round(event.loaded / 1024 / 1024) + 'mb/' + Math.round(event.total / 1024 / 1024) + 'mb';
  var percent = (event.loaded / event.total) * 100;
  _('progressBar').value = Math.round(percent);
  _('percentage_loaded').innerHTML = Math.round(percent) + '%';
  if (Math.round(percent) == 100) {
    _('status').innerHTML = 'Generating Link Please Wait...';
  } else {
    _('status').innerHTML = 'uploading... please wait';
  }
}

function completeHandler(event) {
  _('status').innerHTML = event.target.responseText;
  _('progressBar').value = 0;
}

function errorHandler(event) {
  _('status').innerHTML = 'Upload Failed';
}

function abortHandler(event) {
  _('status').innerHTML = 'Upload Aborted';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1" onchange="uploadFile()"><br>
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <p class="loading">
    <pt id="percentage_loaded"></pt>|
    <!--<pt id="loaded_n_total_bytes"></pt>|
    					<pt id="loaded_n_total_kb"></pt>|-->
    <pt id="loaded_n_total_mb"></pt>|
    <pt id="status"></pt>
  </p>
</form>


我想要做的是当选择一个文件时,它将它作为ajax响应发送到脚本以将文件放在我们的服务器上。当示例代码段与我的实际代码没有区别时,我不知道这是如何产生错误的,除了它周围的额外的东西,但我不知道这可能会影响它。

也许有些聪明的人知道这个问题的答案是什么。

解决方法

而不是这个

function uploadFile() {
  var file = _('file1').files[0];
   ...

试试这个

function uploadFile(event){
 var file=event.target.files[0];
 ...

并且不要忘记改变这一点

<input type="file" name="file1" id="file1" onchange="(event)=>uploadFile(event)"><br>

问题

Oddly enough if I use this code in a jsfiddle it works perfectly

var file = document.getElementById("file");
function CallAlert(){
	alert(file.files[0].name);
}
<form method="post" enctype="multipart/form-data">
 <div>
   <label for="file">Choose file to upload</label>
   <input type="file" id="file" name="file" onchange="CallAlert()">
 </div>
 <div>
   <button>Submit</button>
 </div>
</form>

The result of this is an alert with the name of the file

Now on to my issue using this same method in sorts in my case this returns Uncaught TypeError: Cannot read property '0' of undefined

function _(el) {
  return document.getElementById(el);
}

function uploadFile() {
  var file = _('file1').files[0];
  if (typeof file === 'undefined') {
    _('status').innerHTML = 'ERROR: Please browse for a file before clicking the upload button';
    _('progressBar').value = 0;
  } else {
    $.get('https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php?getsize', function(sizelimit) {
      if (sizelimit > file.size) {
        var formdata = new FormData();
        formdata.append('file1', file);
        formdata.append('size', file.size);
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener('progress', progressHandler, false);
        ajax.addEventListener('load', completeHandler, false);
        ajax.addEventListener('error', errorHandler, false);
        ajax.addEventListener('abort', abortHandler, false);
        ajax.open('POST', 'https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php');
        ajax.send(formdata);
      } else {
        var sizewarn = 'ERROR: The File is too big! The maximum file size is ';
        sizewarn += sizelimit / (1024 * 1024);
        sizewarn += 'MB';
        _('status').innerHTML = sizewarn;
        _('progressBar').value = 0;

      }
    });
  }
}

function progressHandler(event) {
  // _('loaded_n_total_bytes').innerHTML = event.loaded+'bytes/''+event.total+'bytes';
  // _('loaded_n_total_kb').innerHTML = event.loaded/1024+'kb/''+event.total/1024+'kb';
  _('loaded_n_total_mb').innerHTML = Math.round(event.loaded / 1024 / 1024) + 'mb/' + Math.round(event.total / 1024 / 1024) + 'mb';
  var percent = (event.loaded / event.total) * 100;
  _('progressBar').value = Math.round(percent);
  _('percentage_loaded').innerHTML = Math.round(percent) + '%';
  if (Math.round(percent) == 100) {
    _('status').innerHTML = 'Generating Link Please Wait...';
  } else {
    _('status').innerHTML = 'uploading... please wait';
  }
}

function completeHandler(event) {
  _('status').innerHTML = event.target.responseText;
  _('progressBar').value = 0;
}

function errorHandler(event) {
  _('status').innerHTML = 'Upload Failed';
}

function abortHandler(event) {
  _('status').innerHTML = 'Upload Aborted';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1" onchange="uploadFile()"><br>
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <p class="loading">
    <pt id="percentage_loaded"></pt>|
    <!--<pt id="loaded_n_total_bytes"></pt>|
    					<pt id="loaded_n_total_kb"></pt>|-->
    <pt id="loaded_n_total_mb"></pt>|
    <pt id="status"></pt>
  </p>
</form>

What I am trying to do is when a file is selected it sends it as an ajax response to a script to put the file on our server. I dont see how this is producing an error when there is no difference in the example snippet vs my actual code other then the extra stuff around it but I dont see how that could be affecting it.

Perhaps someone smarter then me knows what the answer to this issue is.

解决方法

instead of this

function uploadFile() {
  var file = _('file1').files[0];
   ...

try this

function uploadFile(event){
 var file=event.target.files[0];
 ...

and don't forget to change this

<input type="file" name="file1" id="file1" onchange="(event)=>uploadFile(event)"><br>
相似信息