public JsonResult fileUpload(HttpPostedFileBase file) { var result = new JsonResult(); if (file != null) { var fileName = Path.GetFileName(file.FileName); var physicalPath = Path.Combine(Server.MapPath("~" + ContentGlobals.IMAGEUPLOADDIRECTORY), fileName); var overwrite = System.IO.File.Exists(physicalPath); file.SaveAs(physicalPath); System.IO.File.SetCreationTime(physicalPath, DateTime.UtcNow); string imgPath = ContentGlobals.IMAGEUPLOADDIRECTORY + file.FileName; var media = new Media { Path = imgPath, CreateDate = DateTime.UtcNow }; string htmlstr = overwrite ? "" : ControllerContext.RenderPartialToString("~/Areas/Admin/Views/Shared/Partials/MediaRowPartial.cshtml", media); result.Data = new { html = htmlstr, path = imgPath }; } return result; }
public JsonResult UploadFile(HttpPostedFileBase file, String category = null) { var result = new JsonResult(); string warning = String.Empty; if (file != null) { string uploadToPath = String.IsNullOrEmpty(category) ? ContentGlobals.IMAGEUPLOADDIRECTORY : ContentGlobals.IMAGEUPLOADDIRECTORY + category + "/"; string physicalPath = Path.Combine(Server.MapPath("~" + uploadToPath), Path.GetFileName(file.FileName)); string fullFilename = file.FileName; if (System.IO.File.Exists(physicalPath)) { string filename = Path.GetFileNameWithoutExtension(physicalPath); string extension = Path.GetExtension(physicalPath); int dateHash = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; fullFilename = filename + "_" + dateHash + extension; physicalPath = Path.Combine(Server.MapPath("~" + uploadToPath), fullFilename); warning = "File was renamed."; } try { // Save the file to disk file.SaveAs(physicalPath); // If it's an image, render a thumbnail if (ImageUtils.IsFileAnImage(physicalPath)) { ImageUtils.GenerateThumbnail(uploadToPath + file.FileName); } // Set metadata System.IO.File.SetCreationTime(physicalPath, DateTime.UtcNow); // Return html to be populated client side var media = new Media { Path = uploadToPath + fullFilename, CreateDate = DateTime.UtcNow }; string renderedHtml = ControllerContext.RenderPartialToString("~/Areas/Admin/Views/Shared/Partials/MediaRowPartial.cshtml", media); result.Data = new {success = true, html = renderedHtml, path = media.Path, category, warning}; } catch (SystemException err) { result.Data = new { success = false, error = err}; } } else { result.Data = new {success = false, error = "Could not find specified file"}; } return result; }