After googling, I found that Magic numbers can be used to identify the content type of a file.
In my program, I would like to validate the file content type on server side.
My client side code :
<form action="/Home/Index" method="post" enctype="multipart/form-data">
<input type="file" id="inputFile" value="" onchange="readFileContent(this)" />
<input type="submit" value="Submit" />
</form>
function readFileContent(input) {
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function (e) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/CheckFileType', true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader('X-File-Name', input.files[0].name);
xhr.setRequestHeader('X-File-Type', input.files[0].type);
xhr.setRequestHeader('X-File-Size', input.files[0].size);
xhr.send(input.files[0]);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
};
reader.readAsText(input.files[0]);
}
}
And this is my server side code :
[HttpPost]
public JsonResult CheckFileType()
{
string fileType = Request.Headers["X-File-Type"];
byte[] buffer = new byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, 0, Convert.ToInt32(Request.InputStream.Length));
object result = new { status = "finished" };
return Json(result, JsonRequestBehavior.AllowGet);
}
What is the magic number for a plain-text or .txt file