Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Drew Garratt 44 posts 192 karma points
    May 01, 2013 @ 11:26
    Drew Garratt
    1

    Upload to Media custom FieldType - example

    Hi everyone,

    I'm in one of those projects at the momment where everything I want to do requires something building that there isn't quite a full functional example for. To that end I pressent for your consideration a working example of a custom fieldtype for upload to Umbraco media. It's formed from code in other examples on media creation wrapped up into a Umbraco fieldtype but hopefully having it here on the forum will save a little searching for someone else =)

    using System;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI.WebControls;
    using Umbraco.Core;
    using Umbraco.Core.Models;
    using Umbraco.Core.Services;
    using Umbraco.Forms.Data;
    using Umbraco.Forms.Core;
    using Umbraco.Forms.Core.Controls;
    
    namespace Umbraco.Extensions.Forms
    {
        public class uploadMedia : FieldType
        {
    
            //[Umbraco.Forms.Core.Attributes.Setting("Upload extensions",
            //description = "Allowed file extensions",
            //control = "Umbraco.Forms.Core.FieldSetting.TextField")]
            //public string AllowedExtensions { get; set; }
    
            //[Umbraco.Forms.Core.Attributes.Setting("Media Parent ID",
            //description = "ID of the parent where the media will be saved",
            //control = "Umbraco.Forms.Core.FieldSetting.TextField")]
            //public string MediaParentId { get; set; }
    
            public uploadMedia()
            {
                //Provider
                this.Id = new Guid("xxx-xxx-xxx-xxx-xxx");
                this.Name = "Upload Media";
                this.Description = "Upload file to Umbraco Media";
    
                //FieldType
                this.Icon = "textfield.png";
                this.DataType = FieldDataType.String;
            }
    
            public override string RenderPreview()
            {
                return "<input type='file'/>";
            }
    
            public override string RenderPreviewWithPrevalues(List<object> prevalues)
            {
                return RenderPreview();
            }
    
            public override List<object> ProcessValue(HttpContextBase httpContext)
            {
                List<Object> vals = new List<object>();
    
                //files
                var ms = ApplicationContext.Current.Services.MediaService;
                var cts = ApplicationContext.Current.Services.ContentTypeService;
                bool filesaved = false;
                string _text;
                string mediaPath = "";
                Media m = null;
                var files = httpContext.Request.Files;
                if (files.Count > 0 && files.AllKeys.Contains(this.AssociatedField.Id.ToString()))
                {
                    HttpPostedFileBase file = null;
                    file = files[this.AssociatedField.Id.ToString()];
                    if (file.ContentLength > 0)
                    {
                        if (file.FileName != "")
                        {
                            // Find filename
                            _text = file.FileName;
                            string filename;
                            string _fullFilePath;
    
                            filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
    
                            // create the Media Node
                            // TODO:  get parent id for current category - as selected by user (see below)
                            // - for now just stick these in the media root :: node = -1
                            var mediaType = cts.GetMediaType(1224);
                            m = new Media(
                                filename, 1189, mediaType);
    
                            ms.Save(m);
    
                            // Create a new folder in the /media folder with the name /media/propertyid
                            string mediaRootPath = "~/media/"; // get path from App_GlobalResources
                            string storagePath = mediaRootPath + m.Id.ToString();
    
                            if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(storagePath)))
                                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(storagePath));
    
                            _fullFilePath = HttpContext.Current.Server.MapPath(storagePath) + "\\" + filename;
                            file.SaveAs(_fullFilePath);
    
                            // Save extension
                            string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
                            orgExt = orgExt.ToLower();
                            string ext = orgExt.ToLower();
                            try
                            {
                                m.SetValue("umbracoExtension", ext);
                            }
                            catch { }
    
                            // Save file size
                            try
                            {
                                System.IO.FileInfo fi = new System.IO.FileInfo(_fullFilePath);
                                m.SetValue("umbracoBytes", fi.Length.ToString());
                            }
                            catch { }
    
                            // Check if image and then get sizes, make thumb and update database
                            if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + ext + ",") > 0)
                            {
                                int fileWidth;
                                int fileHeight;
    
                                FileStream fs = new FileStream(_fullFilePath,
                                    FileMode.Open, FileAccess.Read, FileShare.Read);
    
                                System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
                                fileWidth = image.Width;
                                fileHeight = image.Height;
                                fs.Close();
                                try
                                {
                                    m.SetValue("umbracoWidth", fileWidth.ToString());
                                    m.SetValue("umbracoHeight", fileHeight.ToString());
                                }
                                catch { }
    
                                // Generate thumbnails
                                string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
                                generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, ext, fileNameThumb + ".jpg");
    
                                image.Dispose();
                            }
                            mediaPath = "/media/" + m.Id.ToString() + "/" + filename;
    
                            m.SetValue("umbracoFile", mediaPath);
    
                            ms.Save(m);
    
                            vals.Add(filename);
    
                            filesaved = true;
                        }
                    }
    
                }
    
                if (!filesaved)
                {
                    vals.Add("No file saved");
                }
    
                return vals;
            }
    
            protected void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string ext, string thumbnailFileName)
            {
                // Generate thumbnail
                float fx = (float)fileWidth / (float)maxWidthHeight;
                float fy = (float)fileHeight / (float)maxWidthHeight;
                // must fit in thumbnail size
                float f = Math.Max(fx, fy); //if (f < 1) f = 1;
                int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);
    
                // fixes for empty width or height
                if (widthTh == 0)
                    widthTh = 1;
                if (heightTh == 0)
                    heightTh = 1;
    
                // Create new image with best quality settings
                Bitmap bp = new Bitmap(widthTh, heightTh);
                Graphics g = Graphics.FromImage(bp);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    
                // Copy the old image to the new and resized
                Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
                g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
    
                // Copy metadata
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo codec = null;
                for (int i = 0; i < codecs.Length; i++)
                {
                    if (codecs[i].MimeType.Equals("image/jpeg"))
                        codec = codecs[i];
                }
    
                // Set compresion ratio to 90%
                EncoderParameters ep = new EncoderParameters();
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
    
                // Save the new image
                bp.Save(thumbnailFileName, codec, ep);
                bp.Dispose();
                g.Dispose();
    
            }
        }
    }
    
    

    Umbraco 6.0.3 MVC - Contour 3.0.10 

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies