Copied to clipboard

Flag this post as spam?

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


  • Rabea 34 posts 186 karma points
    May 04, 2019 @ 17:18
    Rabea
    0

    File upload to media from form in umbraco 8

    Is there a simple way to upload file to a media folder in Umbraco 8 at controller level, and setting it as a value for a file upload datatype. This is the code i am using currently:

       if (model.FileUpload != null)
                {
                    IMediaService mediaService = Services.MediaService;
                    var media = mediaService.CreateMedia(model.FileUpload.FileName, 1834, "File");
                    media.SetValue("umbracoFile", model.FileUpload.InputStream);
                    mediaService.Save(media);
                    content.SetValue("entry", media);
    
                }
    

    Fileupload has type HttpPostedFileBase.

  • David Armitage 505 posts 2073 karma points
    Jun 21, 2020 @ 03:39
    David Armitage
    0

    Hi Rabea,

    This is how I do it.

     public IMedia InsertImage(HttpPostedFileBase file, int mediaFolderId, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider)
            {
                try
                {
                    IMedia media = _mediaService.CreateMedia(file.FileName, mediaFolderId, Constants.Conventions.MediaTypes.Image);
                    media.SetValue(contentTypeBaseServiceProvider, "umbracoFile", file.FileName, file);
                    _mediaService.Save(media);
                    return media;
                }
                catch (Exception e)
                {
                    _logger.Error<UmbMediaService>("InsertImage | Exception: {0} | Message: {1}", e.InnerException != null ? e.InnerException.ToString() : "", e.Message != null ? e.Message.ToString() : "");
                }
    
                return null;
            }
    

    And this is how I call the method.

    var contentTypeBaseServiceProvider = Current.Services.ContentTypeBaseServices;
                            IMedia image = _umbMediaService.InsertImage(model.Logo, model.MediaFolderId, contentTypeBaseServiceProvider);
    

    Here are the using statements. I am sure not all are necessary. I am sure your visual studios intellisesne will tell you if one of them is not required.

    using Umbraco.Core.Composing;
    using Website.Core.Helpers;
    using Website.Core.Models;
    using Website.Core.Models.EntityModels;
    using Website.Core.Services; 
    

    I can confirm this code works. I literally just re-tested this on a project before posting.

    Regards

    David

Please Sign in or register to post replies

Write your reply to:

Draft