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.
🔄 𝗛𝗼𝘄 𝗱𝗼 𝘆𝗼𝘂 𝗵𝗮𝗻𝗱𝗹𝗲 𝗳𝗶𝗹𝗲 𝘂𝗽𝗹𝗼𝗮𝗱𝘀 𝗶𝗻 𝘆𝗼𝘂𝗿 𝗽𝗿𝗼𝗷𝗲𝗰𝘁𝘀? 𝗗𝗼 𝘆𝗼𝘂 𝗿𝗲𝗹𝘆 𝗼𝗻 𝗰𝗹𝗶𝗲𝗻𝘁-𝘀𝗶𝗱𝗲 𝘃𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 𝗮𝗹𝗼𝗻𝗲, 𝗼𝗿 𝗱𝗼 𝘆𝗼𝘂 𝗽𝗿𝗶𝗼𝗿𝗶𝘁𝗶𝘇𝗲 𝘀𝗲𝗿𝘃𝗲𝗿-𝘀𝗶𝗱𝗲 𝗰𝗵𝗲𝗰𝗸𝘀 𝗳𝗼𝗿 𝘀𝗲𝗰𝘂𝗿𝗶𝘁𝘆? 𝗟𝗲𝘁’𝘀 𝗱𝗶𝘀𝗰𝘂𝘀𝘀!
Top comments (0)