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.
๐ ๐๐ผ๐ ๐ฑ๐ผ ๐๐ผ๐ ๐ต๐ฎ๐ป๐ฑ๐น๐ฒ ๐ณ๐ถ๐น๐ฒ ๐๐ฝ๐น๐ผ๐ฎ๐ฑ๐ ๐ถ๐ป ๐๐ผ๐๐ฟ ๐ฝ๐ฟ๐ผ๐ท๐ฒ๐ฐ๐๐? ๐๐ผ ๐๐ผ๐ ๐ฟ๐ฒ๐น๐ ๐ผ๐ป ๐ฐ๐น๐ถ๐ฒ๐ป๐-๐๐ถ๐ฑ๐ฒ ๐๐ฎ๐น๐ถ๐ฑ๐ฎ๐๐ถ๐ผ๐ป ๐ฎ๐น๐ผ๐ป๐ฒ, ๐ผ๐ฟ ๐ฑ๐ผ ๐๐ผ๐ ๐ฝ๐ฟ๐ถ๐ผ๐ฟ๐ถ๐๐ถ๐๐ฒ ๐๐ฒ๐ฟ๐๐ฒ๐ฟ-๐๐ถ๐ฑ๐ฒ ๐ฐ๐ต๐ฒ๐ฐ๐ธ๐ ๐ณ๐ผ๐ฟ ๐๐ฒ๐ฐ๐๐ฟ๐ถ๐๐? ๐๐ฒ๐โ๐ ๐ฑ๐ถ๐๐ฐ๐๐๐!