我想限制个人资料图片上的文件大小和文件类型。我想只允许.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);
}
答案 0 :(得分: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");
}
}
}
希望这有帮助!
答案 1 :(得分:0)
对于FileSize,您可以检查以下内容:
int maxUploadSize = 1000000
if((int)breader.BaseStream.Length < maxUploadSize){
//upload it
}
要检查ImageType,请查看:https://stackoverflow.com/a/55876/4992212
链接实际上告诉我,图像的初始字节设置为特定值,因此您可以检查初始字节并将它们与您想要的图像类型进行比较。