2016-04-28 149 views
2

我想限制配置文件圖片上的文件大小和文件類型。我只想要允許.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'的鏈接) –

回答

0

您可以添加以下驗證。這樣它不會影響你現有的行動代碼。

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

0

對於文件大小ü可以檢查這樣的事情:

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

要檢查將ImageType看看:https://stackoverflow.com/a/55876/4992212

該鏈接實際上告訴,將圖像的初始字節設置爲一個特定的值,所以你可以檢查最初的字節並將它們與你想要的圖像類型進行比較。

+0

謝謝@Tobias Theel。我用這個文件大小! :) –