Home > Mobile >  How to validate file type in ASP.NET MVC
How to validate file type in ASP.NET MVC

Time:02-10

In my registry of professionals I must allow them to upload their CV but how could I validate that the file type is only .docx and .pdf. Also, which has a maximum weight of 5mb?

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RegistroProfesional(HttpPostedFileBase CV, TB_Profesionales p)
    {
        string n = Path.GetFileName(CV.FileName);
        string Folder = Path.Combine(Server.MapPath("~/ArchivosCV"), n);
        CV.SaveAs(Folder);
        int cant = db.SP_REGISTRAR_PROFESIONAL(p.TIPO, p.NOMBRE, p.APELLIDO, p.DNI,p.EMAIL, p.USUARIO, p.CLAVE, p.SEXO, p.FECHANAC, p.DISTRITO, p.IDSERVICIO, p.DESCRIPCIÓN, p.CV = n, p.PROMEDIOCAL);
        if (cant > 0)
        {
            return RedirectToAction("Login", "Login");
        }
        else
        {
            return RedirectToAction("ListadoProfesional");
        }
    }

CodePudding user response:

Try below code

        try  
        {  
            var supportedTypes = new[] { "docx","pdf"};  
            var fileExt = System.IO.Path.GetExtension(CV.FileName).Substring(1);  
            if (!supportedTypes.Contains(fileExt))  
            {  
                ErrorMessage = "File Extension Is Invalid - Only Upload DOCX and PDF";  
                return ErrorMessage;  
            }  
            else if (CV.ContentLength > (filesize * 1024))  
            {  
                ErrorMessage = "File size Should Be UpTo "   filesize   "KB";  
                return ErrorMessage;  
            }  
            else  
            {  
                ErrorMessage = "File Is Successfully Uploaded";  
                return ErrorMessage;  
            }  
        }  
        catch (Exception ex)  
        {  
            ErrorMessage = "Invalid file";  
            return ErrorMessage;  
        }  
  • Related