Reputation: 4274
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.
This only happens with Firefox. It works fine in 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?
Upvotes: 1
Views: 1795
Reputation: 13089
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.
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>
Upvotes: 3