在“输入类型=“文件""中选择文件后,如何检查文件中的更改? [英] How to check for changes in file after it has been selected in a <input type="file">?

查看:126
本文介绍了在“输入类型=“文件""中选择文件后,如何检查文件中的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在Angular中上传我的文件,我正在这样做:

To upload I file in Angular, I am doing this:

<input type="file" (change)="onFileSelected($event.target.files)"/> 
<button (click)="onStartUpload()"</button>

  public onFileSelected(files: File[]) {
    this.file = files[0];
  }

  public onStartUpload() {
    // Upload the file
  }

这很好用.但是,当我选择一个文件时,然后更改其内容并保存,然后上传它,我的后端响应是这样的:

This works perfectly. But when I select a file, then change its content and save it, and then upload it, my backend response is this:

流意外结束,内容可能已经被读取另一个组件.

Unexpected end of Stream, the content may have already been read by another component.

这仅在Firefox中发生.在Chrome浏览器中工作正常.

更新:使用Chrome的最新更新,它不会发送请求不再.

Update: With Chrome's latest update, it does not send the request anymore.

在浏览器中选择文件后,如何检查文件是否已更改?

How can I check if the file has been changed after I selected it in the browser?

推荐答案

如果使用FileReader对象的实例,则可以利用以下事实:它不会加载被选择后已更改的文件.为了成功上传文件,它必须与选择时保持相同.

If you use an instance of the FileReader object, you can take advantage of the fact that it wont load a file that's been altered after having been selected. In order to upload the file successfully, it must remain the same as it was when it was chosen.

这是一个简短的示例,将进行演示.在Windows下对当前版本的Chrome x64进行了测试.

Here's a short example that will demonstrate. Tested on the current iteration of Chrome x64 under windows.

window.addEventListener('load', onLoaded, false);

function onLoaded(evt) {
  document.querySelector('button').addEventListener('click', onBtnClicked, false);
}

function onBtnClicked(evt) {
  let fileToUpload = document.querySelector('input').files[0];

  const fileReader = new FileReader();
  fileReader.onload = fileLoaded;
  fileReader.onerror = fileError;
  fileReader.readAsText(fileToUpload);
  //	fileReader.readAsArrayBuffer(fileToUpload);
  //	fileReader.readAsBinaryString(fileToUpload);
  //	fileReader.readAsDataURL(fileToUpload);

  function fileLoaded(evt) {
    let fileToUpload = evt.target.result;
  }

  function fileError(evt) {
    console.log('Error loading file');
    console.log(evt.target.error);
  }
}

<input type='file' /><br>
<button>Go</button>

这篇关于在“输入类型=“文件""中选择文件后,如何检查文件中的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆