So I have a file upload script. It works fine but inside my script I have code that changes the file field to "". The change is triggering the onchange event and trys to run the script with no data. What I am looking for is a way to wrap this in an if statement so that the on change event does not fire if the file field is changed back to blank. Im not sure how to wrap this in an if statement due to the xhr.send(fd);}, false); block of code at the end of this script. I can wrap everything above that in an if statement but then it still tries to run the code xhr.send(fd) and gets and error. I need to wrap everything in an if statement or something but cant figure it out. Thanks for any help. Also this works fine in ff and chrome it is IE11 that is throwing the "undefined" error. This makes me think that ff and chrome don't fire onchange event when field is blank but IE does.
document.querySelector('.File').addEventListener('change', function(e) {
var hide = this.getAttribute("id");
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploader.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
document.querySelector('input#'+hide).style.display = 'none';
}
};
xhr.onload = function() {
if (this.status == 200) {
//var resp = JSON.parse(this.response);
//console.log('Server got:', resp);
//add remove link and show file name
filename = file['name'];
document.querySelector('span#'+hide).innerHTML = filename +" <a id="+hide+" class='Remove' href=''>Remove</a>";
//add remove action on click
document.querySelector('a.Remove').addEventListener('click', function(e) {
e.preventDefault();
filename = file['name'];
var show = this.getAttribute("id");
document.querySelector('input#'+show).style.display = 'block';
document.querySelector('input#'+show).value = "";
document.querySelector('span#'+show).innerHTML = "";
//delete file
$.ajax({
url: 'deletefile.php?file='+filename,
method:'GET',
success: function (response) {
},
error: function () {
}
});
});
//show image after upload
//var image = document.createElement('img');
//image.src = resp.dataUrl;
//document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
Aucun commentaire:
Enregistrer un commentaire