We upload any type of files from client to server
using html element
<input id='myFile' type="file" />
And using ASP.NET control
<asp:FileUpload ID='myFile' runat="server" />
We can restrict to upload only some types of file using specifying
the accept attribute value to file content type like bellow
<input id='myFile' type="file" accept="image/gif,
image/jpeg, image/png" />
<asp:FileUpload ID='myFile' runat="server" accept="image/gif,
image/jpeg, image/png" />
File Type Validation
Client side validation
<script type="text/javascript">
var allowFileTypes = ['image/gif', 'image/jpeg', 'image/png'];
function validateFileTypes() {
var files = document.getElementById("myFile").files;
if (files && files[0]) {
//alert(files[0].type);
if (allowFileTypes.indexOf(files[0].type) != -1)
return true;
else {
alert('file
type isn’t allowed');
return false;
}
}
}
</script>
And in server side
validation (C#)
if (myFile.HasFile)
{
if
(myFile.PostedFile.ContentType.ToLower().Contains("image") == false)
{
//message to user
return;
}
else{
//work with the file
}
else{
//work with the file
}
}
File Size Validation
Client side validation
<script type="text/javascript">
var allowFileSize = 50*1024; //50KB
function validateFileSize() {
var files = document.getElementById("myFile").files;
if (files && files[0]) {
//alert(files[0].size);
if (files[0].size <= allowFileSize)
return true;
else {
alert('file
size exceeds the max size 50KB');
return false;
}
}
}
</script>
And in server side
validation (C#)
if (myFile.HasFile)
{
if
(myFile.PostedFile.ContentLength > 50*1024)
{
//message to user
return;
}
else{
//work with the file
}
else{
//work with the file
}
}
Showing the selected image file as preview
We need to add an attribute
onchange to the element like bellow
<input id='myFile' type="file" accept="image/gif,
image/jpeg, image/png" onchange="return showPreview(this);" />
<asp:FileUpload ID='myFile' runat="server" accept="image/gif, image/jpeg, image/png" onchange="return showPreview(this);" />
And the function is bellow
function showPreview(input)
{
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("img#preview").src =
e.target.result;
};
reader.readAsDataURL(input.files[0]);
}
return true;
}
For more about styling the file uploader, see the link http://www.quirksmode.org/dom/inputfile.html