I've been using asp.net web api to upload images to azure blob storage. The code controller code looks like this below and which I found searching the web(can't remember where was a while ago). Anyways this works great. However since other files than images can be uploaded to azure I'd like a way to check if the file is a image aswell. I've seen others asking about this but not been able to implement it using the code below.
Question
How to validate if the file is a image using the code below? And if possible what would be best practice/most safe way to validate this? Any help or input appreciated.
EDIT
Updated with the code i tried to implement, not working though
[HttpPost]
[Route("api/uploadImage")]
[ResponseType(typeof(List<BlobUploadModel>))]
public async Task<IHttpActionResult> PostBlobUpload()
{
try
{
// This endpoint only supports multipart form data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return StatusCode(HttpStatusCode.UnsupportedMediaType);
}
//Added this code to convert to Byte and check if it is a image
Byte[] byteArray = await Request.Content.ReadAsByteArrayAsync();
bool isvalidImage = IsValidImage(byteArray);
if (isvalidImage == false)
{
return BadRequest();
}
// Call service to perform upload, then check result to return as content
var result = await _service.UploadBlobs(Request.Content);
if (result != null && result.Count > 0)
{
return Ok(result);
}
// Otherwise
return BadRequest();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
//Method that is being called to validate if image
public static bool IsValidImage(byte[] bytes)
{
try
{
using (MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException)
{
return false;
}
return true;
}