In my ๐—๐—ผ๐—ฏ ๐—”๐—ฝ๐—ฝ๐—น๐—ถ๐—ฐ๐—ฎ๐˜๐—ถ๐—ผ๐—ป ๐—ง๐—ฟ๐—ฎ๐—ฐ๐—ธ๐—ฒ๐—ฟ project, Iโ€™ve implemented a secure file upload system. While client-side validation (e.g., file size, type) improves user experience, ๐˜€๐—ฒ๐—ฟ๐˜ƒ๐—ฒ๐—ฟ-๐˜€๐—ถ๐—ฑ๐—ฒ ๐˜ƒ๐—ฎ๐—น๐—ถ๐—ฑ๐—ฎ๐˜๐—ถ๐—ผ๐—ป is essential for ๐˜€๐—ฒ๐—ฐ๐˜‚๐—ฟ๐—ถ๐˜๐˜†. It ensures that malicious users cannot bypass your checks and upload unsafe files.

๐—๐—ฎ๐˜ƒ๐—ฎ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜ ๐—Ÿ๐—ผ๐—ด๐—ถ๐—ฐ:

// Client-side file type and size validation
if (file.size > 5 * 1024 * 1024) alert("Max size: 5MB.");
if (file.name.split('.').pop().toLowerCase() !== 'pdf') alert("Only PDF allowed.");

๐—ฆ๐—ฒ๐—ฟ๐˜ƒ๐—ฒ๐—ฟ-๐—ฆ๐—ถ๐—ฑ๐—ฒ ๐—ฉ๐—ฎ๐—น๐—ถ๐—ฑ๐—ฎ๐˜๐—ถ๐—ผ๐—ป (๐—”๐—ฆ๐—ฃ.๐—ก๐—˜๐—ง ๐—–๐—ผ๐—ฟ๐—ฒ):

if (file.Length > 5 * 1024 * 1024) return BadRequest("File size > 5MB.");
if (Path.GetExtension(file.FileName).ToLower() != ".pdf") return BadRequest("Only PDFs.");

๐—จ๐—ฝ๐—น๐—ผ๐—ฎ๐—ฑ๐—ง๐—ฒ๐—บ๐—ฝ๐—ฅ๐—ฒ๐˜€๐˜‚๐—บ๐—ฒ() ๐—Ÿ๐—ผ๐—ด๐—ถ๐—ฐ:

string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "temp-uploads", fileName);
using (var stream = new FileStream(tempPath, FileMode.Create))
{
await file.CopyToAsync(stream); // Save to temp folder
}

๐——๐—ฒ๐—น๐—ฒ๐˜๐—ถ๐—ป๐—ด ๐—ง๐—ฒ๐—บ๐—ฝ ๐—™๐—ถ๐—น๐—ฒ ๐—ฎ๐—ณ๐˜๐—ฒ๐—ฟ ๐——๐—ฎ๐˜๐—ฎ๐—ฏ๐—ฎ๐˜€๐—ฒ ๐—ฆ๐—ฎ๐˜ƒ๐—ฒ:

System.IO.File.Delete(tempPath); // Delete temp file after saving to DB

๐—ช๐—ต๐˜† ๐—ฉ๐—ฎ๐—น๐—ถ๐—ฑ๐—ฎ๐˜๐—ฒ ๐—•๐—ผ๐˜๐—ต ๐—–๐—น๐—ถ๐—ฒ๐—ป๐˜-๐—ฆ๐—ถ๐—ฑ๐—ฒ ๐—ฎ๐—ป๐—ฑ ๐—ฆ๐—ฒ๐—ฟ๐˜ƒ๐—ฒ๐—ฟ-๐—ฆ๐—ถ๐—ฑ๐—ฒ?

  • Client-side validation can be bypassed, so server-side checks are crucial for ๐˜€๐—ฒ๐—ฐ๐˜‚๐—ฟ๐—ถ๐˜๐˜†.
  • Validating file size, type, and MIME type ensures that the file is exactly what it should be.
  • ๐—ฃ๐—ฟ๐—ผ๐˜๐—ฒ๐—ฐ๐˜ ๐˜†๐—ผ๐˜‚๐—ฟ ๐˜€๐˜†๐˜€๐˜๐—ฒ๐—บ from malicious uploads and errors.

๐Ÿ”„ ๐—›๐—ผ๐˜„ ๐—ฑ๐—ผ ๐˜†๐—ผ๐˜‚ ๐—ต๐—ฎ๐—ป๐—ฑ๐—น๐—ฒ ๐—ณ๐—ถ๐—น๐—ฒ ๐˜‚๐—ฝ๐—น๐—ผ๐—ฎ๐—ฑ๐˜€ ๐—ถ๐—ป ๐˜†๐—ผ๐˜‚๐—ฟ ๐—ฝ๐—ฟ๐—ผ๐—ท๐—ฒ๐—ฐ๐˜๐˜€? ๐——๐—ผ ๐˜†๐—ผ๐˜‚ ๐—ฟ๐—ฒ๐—น๐˜† ๐—ผ๐—ป ๐—ฐ๐—น๐—ถ๐—ฒ๐—ป๐˜-๐˜€๐—ถ๐—ฑ๐—ฒ ๐˜ƒ๐—ฎ๐—น๐—ถ๐—ฑ๐—ฎ๐˜๐—ถ๐—ผ๐—ป ๐—ฎ๐—น๐—ผ๐—ป๐—ฒ, ๐—ผ๐—ฟ ๐—ฑ๐—ผ ๐˜†๐—ผ๐˜‚ ๐—ฝ๐—ฟ๐—ถ๐—ผ๐—ฟ๐—ถ๐˜๐—ถ๐˜‡๐—ฒ ๐˜€๐—ฒ๐—ฟ๐˜ƒ๐—ฒ๐—ฟ-๐˜€๐—ถ๐—ฑ๐—ฒ ๐—ฐ๐—ต๐—ฒ๐—ฐ๐—ธ๐˜€ ๐—ณ๐—ผ๐—ฟ ๐˜€๐—ฒ๐—ฐ๐˜‚๐—ฟ๐—ถ๐˜๐˜†? ๐—Ÿ๐—ฒ๐˜โ€™๐˜€ ๐—ฑ๐—ถ๐˜€๐—ฐ๐˜‚๐˜€๐˜€!