【发布时间】:2016-12-16 13:14:49
【问题描述】:
我一直在使用 asp.net web api 将图像上传到 azure blob 存储。代码控制器代码如下所示,我在网上找到了它(不记得前一段时间在哪里)。无论如何,这很好用。但是,由于可以将图像以外的其他文件上传到 azure,所以我想要一种方法来检查文件是否也是图像。我见过其他人问这个问题,但无法使用下面的代码实现它。
问题
如何使用以下代码验证文件是否为图像?如果可能的话,验证这一点的最佳实践/最安全的方法是什么?任何帮助或输入表示赞赏。
编辑
更新了我尝试实现的代码,但不起作用
[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;
}
【问题讨论】:
标签: c# image validation asp.net-web-api azure-blob-storage