Copied to clipboard

Flag this post as spam?

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


  • Debabrata 6 posts 107 karma points
    Jun 01, 2019 @ 14:02
    Debabrata
    0

    Upload Any File Pro-grammatically To Media

    I am trying to upload files programmatically using a html file upload control. The file is getting uploaded and the respective media item is getting created but when I open the media item it's actually showing as file stream not the actual file . Please find my code below

    public void CreateMedia(string mediaName, Guid folderGuid, FileStream file, string extension, string size, object mediaFile)
            {
                var media = _mediaService.CreateMedia(mediaName, folderGuid, "File");
    
                media.SetValue("umbracoFile", file);
                media.SetValue("umbracoExtension", extension);
                media.SetValue("umbracoBytes", size);
    
                _mediaService.Save(media);
            }
    

    enter image description here

  • Mario Lopez 168 posts 952 karma points MVP 3x c-trib
    Jun 02, 2019 @ 10:16
    Mario Lopez
    101

    There's an extension method that allows you to set a value using a Stream with the signature:

    SetValue(this IContentBase content, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, string propertyTypeAlias, string filename, Stream filestream, string culture = null, string segment = null)
    

    To use it include the Umbraco.Core namespace in your class. You don't need to set any other values like bytes or size. Just something like:

    using (var file = new FileStream(Server.MapPath("~/images/image.png"), FileMode.Open))
    {
    
       var media = Services.MediaService.CreateMediaWithIdentity(mediaName, folderId, "File");
       media.SetValue(Services.ContentTypeBaseServices, "umbracoFile", "myfile.png", file);                  
    
       Services.MediaService.Save(media);
    }
    

    Also notice that you should use CreateMediaWithIdentity instead.

  • Debabrata 6 posts 107 karma points
    Jun 02, 2019 @ 16:01
    Debabrata
    0

    Thanks for your suggestion. It's working now after making your suggested changes. Thanks again.

Please Sign in or register to post replies

Write your reply to:

Draft