Copied to clipboard

Flag this post as spam?

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


  • K.Garrein 164 posts 629 karma points
    May 23, 2017 @ 15:11
    K.Garrein
    0

    Programmaticly set a file upload property

    Hey.

    I've searched the forum but couldn't find what I'm looking for.

    I need to programmaticly set a file upload property, but I can't figure out how to do it...

    The file is already uploaded to the server from the public website, but I need to get it in the media section in the backoffice.

    I have found multiple examples online, but they all have a newMedia.SetValue method that has 3 parameters. Intellisense only gives me 2 parameters:

    void Umbraco.Core.Models.IContentBase.SetValue(string propertyTypeAlias, object value);
    

    I tried using a file- and memorystream as the value parameter, but that didn't work either...

    My code (stores the file path in the media object in stead of the actual file :) ):

    string path = System.Web.Hosting.HostingEnvironment.MapPath( "~/Uploads" );
    string filePath = System.IO.Path.Combine( path, "test.pdf" );
    var mediaType = Constants.Conventions.MediaTypes.File;
    var newMedia = mediaSvc.CreateMedia( "test.pdf", -1, mediaType );
    newMedia.SetValue( Constants.Conventions.Media.File, filePath ); 
    mediaSvc.Save( newMedia );
    
  • John Bergman 483 posts 1132 karma points
    May 23, 2017 @ 16:31
    John Bergman
    102

    If you strongly type newMedia, instead of var, you will see a 3-parameter version that takes a filestream as the third parameter. I looked through one of the other media packages to find out how they did it.

  • MuirisOG 382 posts 1284 karma points
    May 23, 2017 @ 16:41
    MuirisOG
    0

    Not sure if you can translate my vb.net into c#, but you are welcome to have a go if you'd like me to post my code here.

    EDIT: Just about to leave, so here is the vb.net code anyway.

            ' this function is called in a for each loop and programmatically adds each image individually
            Public Shared Function importSingleImage(pImage, pTitle, pDescription, pTitleCY, pDescriptionCY) As Integer
                'note: pImage consists of a filename like "/images/myfile.jpg"
                '========== Start initialization of services needed ==============
                Dim cts As IContentTypeService = ApplicationContext.Current.Services.ContentTypeService
                Dim cs As IContentService = ApplicationContext.Current.Services.ContentService
                Dim fs As IFileService = ApplicationContext.Current.Services.FileService
                Dim dts As IDataTypeService = ApplicationContext.Current.Services.DataTypeService
                Dim ms As IMediaService = ApplicationContext.Current.Services.MediaService
                '========== End initialization of services needed ==============
    
                '========== start - get the startnode for the first image ===========
                'note: make sure orgImage media type is set up first as this is the media type used here
                Dim mt As Integer = cts.GetMediaType("Folder").Id
                Dim m As IEnumerable(Of IMedia)
                m = ms.GetMediaOfMediaType(mt)
    
                Dim orgMediaStartNode As Integer
    
                'get the startnode for media in the Media Section
                'Note: the if statement should be done as shown below as otherwise it takes forever
                '      i.e. just look for "orgContentImages", which I set up earlier in the media section
                For Each med As IMedia In m
                    If med.Name = "orgContentImages" Then
                        If med.Trashed = False Then
                            orgMediaStartNode = med.Id
                        End If
                    End If
                Next
                '========== end - get the startnode for the first image ===========
    
    
               '- set up a log file
                Dim path As String = "~/_org/" & DateTime.Today.ToString("yyyy-MM-dd") & ".txt"
                If (Not System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
                    System.IO.File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
                End If
    
                'Steps to using a network location, which is where my files were stored
                ' 1) set up a share on the server folder containing the images
                ' 2) grant permissions on that folder to the network user you want to impersonate
                ' 3) you may need to add the impersonation directive to the web.config for the user you want to impersonate
                Dim imgFilePath As String = "\\myserver\" + System.Web.HttpUtility.UrlDecode(pImage.Replace("/", "\"))
    
                'newImage is a media type for an image file, which uses a media type I created called "orgImage"
                Dim newImage As Media = ms.CreateMedia(pTitle, orgMediaStartNode, "orgImage")
    
                Dim byteData As Byte()
                Try
                    byteData = System.IO.File.ReadAllBytes(imgFilePath)
                Catch
                    ''log an error
                    Using w As StreamWriter = System.IO.File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
                        w.WriteLine(Microsoft.VisualBasic.Constants.vbCrLf & "orgImport Log Entry (importSingleImage): ")
                        w.Write("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))
                        w.WriteLine(" - Not Found: " & pImage)
                    End Using
                    ''return a zero which indicates that the media item wasn't created
                    Return 0
                End Try
    
                Dim imgStream As System.IO.MemoryStream = New MemoryStream(byteData)
                newImage.SetValue("umbracoFile", pImage, imgStream)
    
                'other properties - note I've created my own media type
                'English fields
                newImage.SetValue("en_gb_title", pTitle)
                newImage.SetValue("en_gb_description", pDescription)
                'Welsh fields
                newImage.SetValue("cy_gb_title", pTitleCY)
                newImage.SetValue("cy_gb_description", pDescriptionCY)
    
                Try
                    ms.Save(newImage)
                Catch
                    ''TRACE
                    Using w As StreamWriter = System.IO.File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
                        w.WriteLine(Microsoft.VisualBasic.Constants.vbCrLf & "orgImport Log Entry : Umbraco can't save this file! ")
                        w.WriteLine("User ID: " & System.Web.HttpContext.Current.User.Identity.Name)
                        w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))
                        w.WriteLine("oldImage: " & imgFilePath & "  oldImageDesc: " & pDescription & "  oldImageDescCY: " & pDescriptionCY)
                        w.WriteLine("__________________________")
                    End Using
                    ''END TRACE
                    Return 0
                End Try
    
                'return the media id to the calling function
                Return newImage.Id
    
            End Function
    
  • K.Garrein 164 posts 629 karma points
    May 24, 2017 @ 06:33
    K.Garrein
    0

    Thanks guys!!!

    The strongly typed "IMedia newMedia" (in stead of "var newMedia") did the trick.

    Kind regards.

    K.

Please Sign in or register to post replies

Write your reply to:

Draft