【问题标题】:How to validate only images are uploaded with asp.net web api?如何验证仅使用 asp.net web api 上传的图像?
【发布时间】: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


    【解决方案1】:

    您必须添加验证,如以下链接中所建议的那样检查接收到的 ByteArray,否则返回 BadRequestHow to check if a byte array is a valid image?

    【讨论】:

    • 您认为您可以帮助解决如何在我添加的代码中实现该解决方案。我是初学者,不知道如何一起使用,谢谢你的链接!
    • 你在Request.Content中收到了什么,你能调试检查一下吗?
    • 我想我找到了一种方法来做到这一点,但不确定是否是最佳实践。我添加了代码 Byte[] byteArray = await Request.Content.ReadAsByteArrayAsync();这样我就可以使用您共享的链接中的代码检查 byteArray
    • 关于您对最佳实践的评论,我想说处理服务器端对带宽有开销 - 我没有看到任何其他问题。
    • @mattias:一旦你实现了你的目标,请更新你的代码。这会很有帮助谢谢
    猜你喜欢
    • 2012-08-28
    • 2016-03-09
    • 2018-11-23
    • 1970-01-01
    • 2019-08-07
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多