Copied to clipboard

Flag this post as spam?

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


  • Sjors Pals 617 posts 270 karma points
    Nov 25, 2009 @ 13:42
    Sjors Pals
    0

    Uploading Media and API?

    Hi, i have experience with creating items and users by the API, for a project we want allow users to upload media (and store them as umbraco media items). Problem is that i can not really find samples or information how to do this by using the api. Does someone mabye have a sample or a code snippet how to accomplish this?

  • Sebastiaan Janssen 5061 posts 15523 karma points MVP admin hq
    Nov 25, 2009 @ 13:53
    Sebastiaan Janssen
    0

    Creating media items is as simple as creating new documents.

    Using umbraco.cms.businesslogic.media; do something like this:

    var imageType = MediaType.GetByAlias("Image");
    Media.MakeNew("myTitle", imageType, new User(0), 1234);

    The "1234" is the parent id under which the media item should be created.

  • Sjors Pals 617 posts 270 karma points
    Nov 25, 2009 @ 14:34
    Sjors Pals
    0

    Ok Sebastiaan got that working, but how do i get the file i uploaded in my temp dir to that media item?

    Do i have to manually create the upload folder, and resize it, or are there methods in the api to do that?

  • Sjors Pals 617 posts 270 karma points
    Nov 25, 2009 @ 15:13
    Sjors Pals
    0

    Ok its working now, found a sample on the old board:

     

    [code]

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using umbraco;
    using umbraco.cms;
    using umbraco.cms.businesslogic.member;
    using umbraco.cms.businesslogic.web;
    using umbraco.BusinessLogic;
    using umbraco.cms.businesslogic.media;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    using System.Xml;


    namespace umbraco.presentation.usercontrols
    {
        public partial class MediaUpload : System.Web.UI.UserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {

            }
            protected void btnAdd_Click(object sender, EventArgs e)
            {
                string mediaPath = "";
                if (FileUpload1.HasFile)
                {

                        FileUpload1.SaveAs(@"C:\\temp\" + FileUpload1.FileName);
                       
                        string _text = FileUpload1.PostedFile.FileName;
                        string filename;
                        string _fullFilePath;
                        filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
                    
                        var imageType = MediaType.GetByAlias("Image");
                        //Hardcoded Node 1045
                        Media m = Media.MakeNew(filename, imageType, new User(0), 1045);

                        // Create a new folder in the /media folder with the name /media/propertyid
                        System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(GlobalSettings.Path + "/../media/" + m.Id.ToString()));
                        _fullFilePath = System.Web.HttpContext.Current.Server.MapPath(GlobalSettings.Path + "/../media/" + m.Id.ToString() + "/" + filename);
                        FileUpload1.PostedFile.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.getProperty("umbracoExtension").Value = ext;
                        }
                        catch { }

                        // Save file size
                        try
                        {
                            System.IO.FileInfo fi = new FileInfo(_fullFilePath);
                            m.getProperty("umbracoBytes").Value = 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.getProperty("umbracoWidth").Value = fileWidth.ToString();
                                m.getProperty("umbracoHeight").Value = 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.getProperty("umbracoFile").Value = mediaPath;
                        m.XmlGenerate(new XmlDocument());

                      
                }
            }
            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(Encoder.Quality, 90L);

                // Save the new image
                bp.Save(thumbnailFileName, codec, ep);
                bp.Dispose();
                g.Dispose();

            }
        }
    }

    [/code]

  • Sebastiaan Janssen 5061 posts 15523 karma points MVP admin hq
    Nov 25, 2009 @ 15:20
    Sebastiaan Janssen
    0

    Cool, could you provide a link to the old post, I tried Googling but couldn't find it (or fix the codesample in this post)?

  • Sjors Pals 617 posts 270 karma points
    Nov 26, 2009 @ 15:34
    Sjors Pals
    0

    Mmmm another try:

     

    [code]

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using umbraco;
    using umbraco.cms;
    using umbraco.cms.businesslogic.member;
    using umbraco.cms.businesslogic.web;
    using umbraco.BusinessLogic;
    using umbraco.cms.businesslogic.media;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    using System.Xml;


    namespace umbraco.presentation.usercontrols
    {
        public partial class MediaUpload : System.Web.UI.UserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {

            }
            protected void btnAdd_Click(object sender, EventArgs e)
            {
                string mediaPath = "";
                if (FileUpload1.HasFile)
                {

                        FileUpload1.SaveAs(@"C:\\temp\" + FileUpload1.FileName);
                       
                        string _text = FileUpload1.PostedFile.FileName;
                        string filename;
                        string _fullFilePath;
                        filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
                    
                        var imageType = MediaType.GetByAlias("Image");
                        //ROOT NODE Onder welke Media folder je hem opslaat!!!
                        Media m = Media.MakeNew(filename, imageType, new User(0), 1045);

                        // Create a new folder in the /media folder with the name /media/propertyid
                        System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(GlobalSettings.Path + "/../media/" + m.Id.ToString()));
                        _fullFilePath = System.Web.HttpContext.Current.Server.MapPath(GlobalSettings.Path + "/../media/" + m.Id.ToString() + "/" + filename);
                        FileUpload1.PostedFile.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.getProperty("umbracoExtension").Value = ext;
                        }
                        catch { }

                        // Save file size
                        try
                        {
                            System.IO.FileInfo fi = new FileInfo(_fullFilePath);
                            m.getProperty("umbracoBytes").Value = 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.getProperty("umbracoWidth").Value = fileWidth.ToString();
                                m.getProperty("umbracoHeight").Value = 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.getProperty("umbracoFile").Value = mediaPath;
                        m.XmlGenerate(new XmlDocument());

                      
                }
            }
            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(Encoder.Quality, 90L);

                // Save the new image
                bp.Save(thumbnailFileName, codec, ep);
                bp.Dispose();
                g.Dispose();

            }
        }
    }

    [/code]

  • Sjors Pals 617 posts 270 karma points
    Nov 26, 2009 @ 15:37
    Sjors Pals
    3
Please Sign in or register to post replies

Write your reply to:

Draft