如何在 ASP.NET MVC 中验证文件类型
How to validate file type in ASP.NET MVC
在我的专业人员注册表中,我必须允许他们上传他们的简历,但我如何才能验证文件类型是否仅为 .docx 和 .pdf。另外,哪个最大重量为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");
}
}
试试下面的代码
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;
}
在我的专业人员注册表中,我必须允许他们上传他们的简历,但我如何才能验证文件类型是否仅为 .docx 和 .pdf。另外,哪个最大重量为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");
}
}
试试下面的代码
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;
}