public void ViewLostFocus() { if (Count == 1 && BlogFile != null) { BlogFile.Save(); } }
public void ViewLostFocus() { if (Count == 1) { BlogFile?.Save(); } }
/// <summary> /// Load the content of the file to the object /// </summary> /// <param name="id">The blog item to get the file from</param> /// <param name="file">The file to have the content populated into</param> /// <returns>The populated Blog File object</returns> public override BlogFile LoadFile(String id, BlogFile file) { try { // Generate the path for the file item String fileLocation = BlogFilePath(id, file.Id, Path.GetExtension(file.Filename).Replace(".", "")); // Calculate the relative directory based on the path String combinedPath = Path.Combine(Configuration.Environment.WebRootPath, fileLocation); // Get the directory portion from the combined Path String fileDirectory = Path.GetDirectoryName(combinedPath); // If the directory doesn't exist then create it if (Directory.Exists(fileDirectory)) { // Read the file contents file.Content = File.ReadAllBytes(combinedPath); } } catch (Exception ex) { throw BlogException.Passthrough(ex, new CouldNotLoadBlogException(ex)); } // Send the file back return(file); }
/// <summary> /// Save a file to a blog item /// </summary> /// <param name="id">The blog item to save the file against</param> /// <param name="file">The file to be saved</param> /// <returns>The saved file</returns> public override BlogFile SaveFile(String id, BlogFile file) { try { // Make sure that there is an identifier file.Id = ((file.Id ?? "") == "") ? NewId() : file.Id; // Generate the path for the file item String fileLocation = BlogFilePath(id, file.Id, Path.GetExtension(file.Filename).Replace(".", "")); // Calculate the relative directory based on the path String combinedPath = Path.Combine(Configuration.Environment.WebRootPath, fileLocation); // Get the directory portion from the combined Path String fileDirectory = Path.GetDirectoryName(combinedPath); // If the directory doesn't exist then create it if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } // Write the file contents File.WriteAllBytes(combinedPath, file.Content); } catch (Exception ex) { throw BlogException.Passthrough(ex, new CouldNotSaveBlogException(ex)); } // Send the file back return(file); }
/// <summary> /// Build the singular attachment editor /// </summary> /// <param name="file">The file (attachment) to be displayed</param> /// <param name="viewModel">The view model that contains the relevant templates</param> /// <returns>The Html Content for the attachment editor</returns> private static IHtmlContent EditAttachment(IBlogItem item, BlogFile file, BlogViewModelBase viewModel) => ContentFill(BlogViewTemplatePart.Attachment_Item, new List <BlogViewTemplateReplacement>() { new BlogViewTemplateReplacement(BlogViewTemplateField.Common_Controller_Url, viewModel.ControllerUrl, false), new BlogViewTemplateReplacement(BlogViewTemplateField.Attachment_Title, file.Title, false), new BlogViewTemplateReplacement(BlogViewTemplateField.Attachment_Url, AttachmentUrl(item, file, viewModel), false) }, viewModel);
/// <summary> /// Upload a file to the server /// </summary> /// <param name="blogItem">The blog item the file is attached to</param> /// <param name="title">The title of the attachment</param> /// <param name="file">The raw file to be attached</param> /// <returns>The blog file that was created </returns> public BlogFile UploadFile(IBlog blog, IBlogItem blogItem, String title, IFormFile file) { // The blog file to be returned BlogFile blogFile = null; // Make sure there is actually a file if (file != null) { if (blogItem != null) { // The content of the file ready to pass to the data provider Byte[] fileContent = null; // Empty by default // Create a memory stream to read the file using (MemoryStream memoryStream = new MemoryStream()) { file.CopyTo(memoryStream); // Copy the file in to a memory stream fileContent = memoryStream.ToArray(); // convert the steam of data to a byte array memoryStream.Close(); // It's in a using anyway but just incase } // Something to save? if (fileContent != null && fileContent.Length != 0) { // Get the content header ContentDispositionHeaderValue parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition); // Create the new blog file for saving blogFile = new BlogFile() { Content = fileContent, Filename = parsedContentDisposition.FileName.Replace("\"", ""), Tags = new List <String>(), Title = title ?? ("File: " + Guid.NewGuid().ToString()) }; // Add the file to the blog file list blogItem.Files.Add(blogFile); // Save the blog item and with it the new file blog.Save(blogItem); } } } // Saved so do the common redirect return(blogFile); }
public virtual IActionResult GetAttachment(String id, String fileId) { // Bytes to send back Byte[] content = null; // No content by default String contentType = BlogFile.DefaultMimeType; // Default content type is plain text String fileName = ""; // Default filename // Get the blog that is for this controller instance if (Current != null) { // Get the blog item IBlogItem blogItem = Current.Get(new BlogHeader() { Id = Current.Parameters.Provider.DecodeId(id) }); // Did the "Get" actually work? if (blogItem != null && blogItem.Header.Id != "") { // Get the blog item related to the request BlogFile blogFile = blogItem.Files.Where(file => file.Id == fileId).FirstOrDefault(); // Does this file exist under this blog item? if (blogFile != null) { // Populate the file class with the data from the provider blogFile = Current.Parameters.Provider.LoadFile(blogItem.Header.Id, blogFile); // Content was returned for this request? if (blogFile != null && blogFile.Id != "") { // Assign the varaibles for the return stream contentType = blogFile.ContentType; // Work out the content type for the header fileName = blogFile.Filename; // Get the origional filename content = blogFile.Content; // Get the returned content type // Return the content here return(File(content, contentType, fileName)); } } } } // Must have failed to have arrived here return(File((Byte[])null, BlogFile.DefaultMimeType, "")); }
public IActionResult FileBrowserUpload(String id, String CKEditorFuncNum, String Source, [FromForm] IFormFile Upload) { // The file to be attached CKEditorUploadResponse result = new CKEditorUploadResponse() { }; // Get the blog that is for this controller instance if (Current != null) { // Get the blog item IBlogItem blogItem = Current.Get(new BlogHeader() { Id = Current.Parameters.Provider.DecodeId(id) }); if (blogItem != null) { // Which editor was requested? switch (Source) { // Was CK Editor being used? If so set certain properties of the view model case "CKEditor": // If the file upload is goodthen BlogFile file = UploadFile(Current, blogItem, Upload.FileName, Upload); result.Uploaded = 1; result.Filename = Upload.FileName; result.Url = HtmlHelpers.AttachmentUrl(blogItem, file, ControllerName); break; } } } // Return the object as the result return(Json(result)); }
=> throw new NotImplementedException(); // Not implemented in the base class /// <summary> /// Load the content of the file to the object /// </summary> /// <param name="id">The blog item to get the file from</param> /// <param name="file">The file to have the content populated into</param> /// <returns>The populated Blog File object</returns> public virtual BlogFile LoadFile(String id, BlogFile file) => throw new NotImplementedException(); // Not implemented in the base class
/// <summary> /// Default constructor /// </summary> public FileBrowserUploadViewModel() : base() { BlogFile = new BlogFile(); }
/// <summary> /// Base implementation of the attachment url for putting together the relative path /// </summary> /// <param name="item">The blog item</param> /// <param name="file">The file in the blog item to link to</param> /// <param name="ControllerName">The name of the controller to be linked to</param> /// <returns></returns> public static String AttachmentUrl(IBlogItem item, BlogFile file, String ControllerName) => $"{FormatControllerName(ControllerName)}/item/{item.Header.Id}/attachment/{file.Id}";
/// <summary> /// The translated attachment url (Will not be direct but /// through a controller to relay the data) /// </summary> /// <param name="item">The blog item the file is attached to</param> /// <param name="file">The file to provide the url for</param> /// <param name="viewModel">The view model that containers the controller base url (incase there are multiple blogs)</param> /// <returns>The url for the file attachment</returns> public static String AttachmentUrl(IBlogItem item, BlogFile file, BlogViewModelBase viewModel) => AttachmentUrl(item, file, viewModel.RelativeControllerUrl);
public async Task <IActionResult> Edit(int id, [Bind("BlogId,BlogTitle,BlogDate,BlogEndDate,BlogDetail,BlogPicTitle,BlogCatId,BlogStatus,BlogCreateDate,BlogCreateBy")] Blog blog, List <IFormFile> files, IFormFile uploadPic, string picold, List <IFormFile> filesUpload, string Startdate, string EndDate) { /*Check Session */ var page = "3"; var typeofuser = ""; var PermisionAction = ""; // CheckSession if (string.IsNullOrEmpty(HttpContext.Session.GetString("Username"))) { Alert("คุณไม่มีสิทธิ์ใช้งานหน้าดังกล่าว", NotificationType.error); return(RedirectToAction("Index", "Home")); } else { typeofuser = HttpContext.Session.GetString("TypeOfUserId"); PermisionAction = HttpContext.Session.GetString("PermisionAction"); if (PermisionHelper.CheckPermision(typeofuser, PermisionAction, page) == false) { Alert("คุณไม่มีสิทธิ์ใช้งานหน้าดังกล่าว", NotificationType.error); return(RedirectToAction("Index", "Home")); } } /*Check Session */ var date1 = Startdate.Substring(6, 4) + "-" + Startdate.Substring(3, 2) + "-" + Startdate.Substring(0, 2) + " 00:00:00"; var date2 = EndDate.Substring(6, 4) + "-" + EndDate.Substring(3, 2) + "-" + EndDate.Substring(0, 2) + " 23:59:59"; var sdate1 = Startdate; var sdate2 = EndDate; var rdate1 = Startdate; var rdate2 = EndDate; if (id != blog.BlogId) { return(NotFound()); } if (ModelState.IsValid) { try { blog.BlogUpdateBy = HttpContext.Session.GetString("Username"); blog.BlogUpdateDate = DateTime.Now; var check = 0; if (uploadPic == null || uploadPic.Length == 0) { blog.BlogPicTitle = picold; check = 1; } if (check == 0) { if (uploadPic.ContentType.IndexOf("image", StringComparison.OrdinalIgnoreCase) < 0) { blog.BlogPicTitle = picold; check = 1; } } if (check == 0) { string pathImage = "/images/BlogTitle/"; string pathSave = $"wwwroot{pathImage}"; if (!Directory.Exists(pathSave)) { Directory.CreateDirectory(pathSave); } if (!Directory.Exists(pathSave + "/32/")) { Directory.CreateDirectory(pathSave + "/32/"); } if (!Directory.Exists(pathSave + "/64/")) { Directory.CreateDirectory(pathSave + "/64/"); } if (!Directory.Exists(pathSave + "/128/")) { Directory.CreateDirectory(pathSave + "/128/"); } if (!Directory.Exists(pathSave + "/256/")) { Directory.CreateDirectory(pathSave + "/256/"); } if (!Directory.Exists(pathSave + "/512/")) { Directory.CreateDirectory(pathSave + "/512/"); } if (!Directory.Exists(pathSave + "/1028/")) { Directory.CreateDirectory(pathSave + "/1028/"); } string fileName = Path.GetFileNameWithoutExtension(uploadPic.FileName); string extension = Path.GetExtension(uploadPic.FileName); fileName = fileName + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + extension; var path = Path.Combine(Directory.GetCurrentDirectory(), pathSave, fileName); using (var stream = new FileStream(path, FileMode.Create)) { await uploadPic.CopyToAsync(stream); } ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/32/" + fileName, 32); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/64/" + fileName, 64); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/128/" + fileName, 128); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/256/" + fileName, 256); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/512/" + fileName, 512); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/1028/" + fileName, 1028); blog.BlogPicTitle = fileName; } blog.BlogDate = Convert.ToDateTime(date1); blog.BlogEndDate = Convert.ToDateTime(date2); _context.Update(blog); await _context.SaveChangesAsync(); var IDBLOG = blog.BlogId; if (files != null && files.Count > 0) { //Upload file string pathImage = "/images/Board/"; string pathSave = $"wwwroot{pathImage}"; if (!Directory.Exists(pathSave)) { Directory.CreateDirectory(pathSave); } if (!Directory.Exists(pathSave + "/32/")) { Directory.CreateDirectory(pathSave + "/32/"); } if (!Directory.Exists(pathSave + "/64/")) { Directory.CreateDirectory(pathSave + "/64/"); } if (!Directory.Exists(pathSave + "/128/")) { Directory.CreateDirectory(pathSave + "/128/"); } if (!Directory.Exists(pathSave + "/256/")) { Directory.CreateDirectory(pathSave + "/256/"); } if (!Directory.Exists(pathSave + "/512/")) { Directory.CreateDirectory(pathSave + "/512/"); } if (!Directory.Exists(pathSave + "/1028/")) { Directory.CreateDirectory(pathSave + "/1028/"); } foreach (IFormFile item in files) { if (item.Length > 0) { string fileName = Path.GetFileNameWithoutExtension(item.FileName); string extension = Path.GetExtension(item.FileName); fileName = fileName + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + extension; var path = Path.Combine(Directory.GetCurrentDirectory(), pathSave, fileName); using (var stream = new FileStream(path, FileMode.Create)) { await item.CopyToAsync(stream); } ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/32/" + fileName, 32); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/64/" + fileName, 64); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/128/" + fileName, 128); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/256/" + fileName, 256); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/512/" + fileName, 512); ImageResizeHelper.Image_resize(pathSave + fileName, pathSave + "/1028/" + fileName, 1028); var blogPic = new BlogPic { BlogPicName = fileName, BlogId = IDBLOG }; _context.BlogPics.Add(blogPic); _context.SaveChanges(); } } } //upload File if (filesUpload != null && filesUpload.Count > 0) { //Upload file string pathImage = "/File/Board/"; string pathSave = $"wwwroot{pathImage}"; if (!Directory.Exists(pathSave)) { Directory.CreateDirectory(pathSave); } foreach (IFormFile item in filesUpload) { if (item.Length > 0) { string fileName = Path.GetFileNameWithoutExtension(item.FileName); string extension = Path.GetExtension(item.FileName); fileName = fileName + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + extension; var path = Path.Combine(Directory.GetCurrentDirectory(), pathSave, fileName); using (var stream = new FileStream(path, FileMode.Create)) { await item.CopyToAsync(stream); } var blogFile = new BlogFile { BlogFileName = fileName, BlogFileType = extension, BlogId = IDBLOG }; _context.BlogFiles.Add(blogFile); _context.SaveChanges(); } } } } catch (DbUpdateConcurrencyException) { if (!BlogExists(blog.BlogId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(blog)); }
/// <summary> /// Default constructor /// </summary> public FileBrowserViewModel() : base() { // Defaults File = new BlogFile(); Item = new BlogItem(); }
/// <summary> /// Delete a file in a blog item /// </summary> /// <param name="id">The blog item to delete the file against</param> /// <param name="file">The file to be deleted</param> /// <returns>If the file was deleted successfully</returns> public override Boolean DeleteFile(String id, BlogFile file) { return(true); }