How to determine if user selected a file for file upload?
JavascriptHtmlUploadJavascript Problem Overview
If I have a
<input id="uploadFile" type="file" />
tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.
In FF, I just do:
var selected = document.getElementById("uploadBox").files.length > 0;
But that doesn't work in IE.
Javascript Solutions
Solution 1 - Javascript
This works in IE (and FF, I believe):
if(document.getElementById("uploadBox").value != "") {
// you have a file
}
Solution 2 - Javascript
this piece of code works in my local environment, hope it will also works in live
var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
alert('Must Select any of your photo for upload!');
nme.focus();
return false;
}
Solution 3 - Javascript
function validateAndUpload(input){
var URL = window.URL || window.webkitURL;
var file = input.files[0];
if (file) {
var image = new Image();
image.onload = function() {
if (this.width) {
console.log('Image has width, I think it is real image');
//TODO: upload to backend
}
};
image.src = URL.createObjectURL(file);
}
};
<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>
Call this function on change .
Solution 4 - Javascript
You can use:
var files = uploadFile.files;
if (files.length == 0) { console.log(true) } else { console.log(false) }
if (files[0] == undefined) { console.log(true) } else { console.log(false) }
if (files[0] == null) { console.log(true) } else { console.log(false) }
All three give the same result.
Solution 5 - Javascript
You can check it in asp.net using c#:
html:
<input id="FileID" runat="server" type="file"/>
c#:
if(FileID.PostedFile.FileName != "")
{
// do whatever you want if file is selected
}
else
{
//do whatever you want if no file is selected
}