Copied to clipboard

Flag this post as spam?

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


  • ramzdam 6 posts 27 karma points
    Jun 15, 2020 @ 17:15
    ramzdam
    0

    Auto create media programatically

    Hi I want to create a media programatically. So the idea is that I have a folder in my root directory and upon clicking a button the script/api will scan the folder and if there's a file in there it will create a Media entry programatically. Now the reason I do this is that I'm planning to make this a background service and I'm planning to upload a very large file. Uploading it through the backend or frontend will take time but if I can do this at the background it will be great. Now I have a very beginner idea on C# and umbraco. I've been looking for codes to do this but can't find any. Hope someone here can help me. I want it to automatically create media using Umbraco 7. Any idea on how to achieve this? Would appreciate any working sample or URL that leads me to the solution. Thanks again

  • David Armitage 509 posts 2079 karma points
    Aug 01, 2020 @ 03:34
    David Armitage
    0

    Hi Ramzdam,

    These methods will help you that I wrote.

    public static IMedia AddMediaFile(int parentId, HttpPostedFile file)
            {
                var ms = ApplicationContext.Current.Services.MediaService;
                var mediaMap = ms.CreateMedia(file.FileName, parentId, Umbraco.Core.Constants.Conventions.MediaTypes.File);
                mediaMap.SetValue("umbracoFile", file.FileName, file.InputStream);
                ms.Save(mediaMap);
                return mediaMap;
            }
    
            public static IMedia AddMediaFile(int parentId, HttpPostedFileBase file, string fileName, string extension)
            {
                var ms = ApplicationContext.Current.Services.MediaService;
                var mediaMap = ms.CreateMedia(fileName, parentId, Umbraco.Core.Constants.Conventions.MediaTypes.File);
                mediaMap.SetValue("umbracoFile", fileName + extension, file.InputStream);
                ms.Save(mediaMap);
                return mediaMap;
            }
    

    You will need to tweak these since the methods are accepting an HttpPostedFileBase. From your desicription what you will need to do is read the file, concert it into a stream and pass this in the one of the methods I gave you above.

    Regards

    David

Please Sign in or register to post replies

Write your reply to:

Draft