我一直在使用 asp.net web api 将图像上传到 azure blob 存储。代码 Controller 代码如下所示,是我在网上搜索发现的(不记得刚才在哪里)。无论如何,这很好用。但是,由于可以将图像以外的其他文件上传到 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;
}
最佳答案
您必须按照以下链接中的建议添加验证以检查收到的 ByteArray,否则返回 BadRequest
。
How to check if a byte array is a valid image?
关于c# - 如何仅验证使用 asp.net web api 上传的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38868565/