Skip to content

Instantly share code, notes, and snippets.

@nesticle8bit
Last active February 15, 2019 10:58
Show Gist options
  • Save nesticle8bit/1c95f8b410f07edc1a1fc3bf692a33af to your computer and use it in GitHub Desktop.
Save nesticle8bit/1c95f8b410f07edc1a1fc3bf692a33af to your computer and use it in GitHub Desktop.
Upload file to Server
[HttpPost]
[AjaxValidationAntiForgeryToken]
public JsonResult UploadFileToServer(HttpPostedFileBase file, int? id, string deleteFile)
{
var response = new JsonResultBody();
try
{
response.Status = System.Net.HttpStatusCode.OK;
if(file != null)
{
var folder = $"{DateTime.Now.ToString("yyyy-MM-dd")}";
var url = Server.MapPath($"~/Files/OportunidadesMejora/{folder}/{id}/");
//Revisar si existe el directorio, sino crearlo
if (Directory.Exists(url) == false)
Directory.CreateDirectory(url);
var fileToUpload = $"{file.FileName}";
var fileExtension = Path.GetExtension(fileToUpload);
string filename = Path.GetFileNameWithoutExtension(fileToUpload);
file.SaveAs(url + filename + fileExtension);
response.Data = new {
Mensaje = $"El archivo {evidencia.Nombre} se ha guardado correctamente"
};
}
}
catch (DbEntityValidationException ex)
{
response.Status = System.Net.HttpStatusCode.InternalServerError;
foreach (DbEntityValidationResult result in ex.EntityValidationErrors)
{
response.Errors = (from ve in result.ValidationErrors select ve.ErrorMessage).ToList();
}
}
catch (Exception exAplicacion)
{
response.Status = System.Net.HttpStatusCode.InternalServerError;
response.Errors.Add(exAplicacion.Message);
}
return Json(response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment