【问题标题】:I want to restrict the fileupload to only accept .jpg and .png files, and to restrict the filesize [duplicate]我想将文件上传限制为仅接受 .jpg 和 .png 文件,并限制文件大小 [重复]
【发布时间】:2016-08-22 22:01:36
【问题描述】:

我想限制个人资料图片上的文件大小和文件类型。我只想允许 .jpg 和 .png 图片,并且我还想只允许最大文件大小,例如 1 兆字节。在您下方,您可以看到我的无限制上传文件的代码。我正在使用base64。我需要在上传图片之前检查文件类型和文件大小,但我真的不知道如何以及在哪里。如果您需要查看我的更多代码,请告诉我。非常感谢。

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ChangePic(IndexViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByIdAsync(User.GetUserId());

            var breader = new BinaryReader(model.ProfilePic.OpenReadStream());

            var byteImage = breader.ReadBytes((int)breader.BaseStream.Length);

            user.ProfilePic = byteImage;

            var result = await _userManager.UpdateAsync(user);
            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "Profile info updated");
                return RedirectToAction(nameof(ManageController.Index), "Manage");
            }
            AddErrors(result);

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

【问题讨论】:

标签: c# .net asp.net-mvc entity-framework file-upload


【解决方案1】:

您可以添加以下验证。这样它就不会影响您现有的操作代码。

public class IndexViewModel : IValidatableObject
{
    public HttpPostedFileBase ProfilePic { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {

        if (ProfilePic.ContentType != "image/png" && ProfilePic.ContentType != "image/jpeg")
        {
            yield return new ValidationResult("Application only supports PNG or JPEG image types");
        }

        if (ProfilePic.ContentLength > 1000000)
        {
            yield return new ValidationResult("File size must not exceed 1MB");
        }

    }
}

希望这会有所帮助!

【讨论】:

  • 非常感谢!非常感谢@heymega :)
  • 没问题,欢迎来到 SO。
【解决方案2】:

对于 FileSize,您可以检查如下内容:

int maxUploadSize = 1000000 
if((int)breader.BaseStream.Length < maxUploadSize){
//upload it
}

要检查 ImageType,请查看:https://stackoverflow.com/a/55876/4992212

链接实际上表明,图像的初始字节设置为特定值,因此您可以检查初始字节并将它们与您想要的图像类型进行比较。

【讨论】:

  • 谢谢@Tobias Theel。我用它来确定文件大小! :)
猜你喜欢
  • 1970-01-01
  • 2020-08-24
  • 2017-05-19
  • 2022-10-26
  • 1970-01-01
  • 2011-01-29
  • 2017-03-09
  • 2011-01-13
  • 1970-01-01
相关资源
最近更新 更多