10 Aralık 2020

Pdf Türünde Dosya Kontrolü İçin Attribute

public class IsPdfFileAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
if (value != null)
{
var files = (List<IFormFile>)value;
if (files.Count > 0)
{
var areAllFilesZip = true;
foreach (var file in files)
{
if (file.FileName.EndsWith(".pdf") && file.ContentType == "application/pdf"
)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var byteArray = ms.ToArray();
var content = System.Text.Encoding.UTF8.GetString(byteArray);
if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
{
areAllFilesZip = false;
break;
}

if (!content.StartsWith("%PDF"))
{
areAllFilesZip = false;
break;
}
}
}
else
{
areAllFilesZip = false;
break;
}
}
if (areAllFilesZip)
return ValidationResult.Success;
}
}
}
catch (Exception ex)
{

}
return new ValidationResult("Sadece PDF dosya yükleyebilirsiniz!");
}

public class SampleModel
{
[IsPdfFile]
public List<IFormFile> SamplePdfFile { get; set; }
}

// HomeController.cs
   public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult Index([FromForm] SampleModel model)
{
return View(model);
}


//Index.cshtml
@{
@model WebApplication1.Models.SampleModel
}

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="SamplePdfFile" accept="application/pdf" required>
<input type="submit" />
if (!Html.ViewData.ModelState.IsValid)
{
<hr />
<div asp-validation-summary="All"></div>
}