我想限制文件上传只接受.jpg和.png文件,并限制文件大小

我想限制文件上传只接受.jpg和.png文件,并限制文件大小

问题描述:

我想限制配置文件图片上的文件大小和文件类型。我只想要允许.jpg和.png图片,并且我还希望仅允许最大文件大小为1兆字节。在你看到我的代码上传一个没有限制的文件。我正在使用base64。我需要在图片上传之前检查文件类型和文件大小,但我真的不知道如何以及在哪里。如果您需要查看更多我的代码,请告诉我。非常感谢你。我想限制文件上传只接受.jpg和.png文件,并限制文件大小

[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); 
    } 
+1

您可以使用验证属性,以便获得客户端和服务器端验证 - 请参阅[FileTypeAttribute的此示例](http://stackoverflow.com/questions/33414158/checking-image-mime-size-etc- in-mvc/33426397#33426397)(并且包含指向'FileSizeAttribute'的链接) –

您可以添加以下验证。这样它不会影响你现有的行动代码。

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"); 
     } 

    } 
} 

希望这有助于!

+0

非常感谢!非常感谢@heymega :) –

+0

没问题,欢迎来到SO。 – heymega

对于文件大小ü可以检查这样的事情:

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

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

该链接实际上告诉,将图像的初始字节设置为一个特定的值,所以你可以检查最初的字节并将它们与你想要的图像类型进行比较。

+0

谢谢@Tobias Theel。我用这个文件大小! :) –