fredag den 19. december 2014

Creating media items from a .NET Stream

From time to time, we need to create media items from .NET Stream objects (mostly when a user has uploaded a file).

In this case, this little helper function makes it really easy.

The parentItem is the parent item where them media item should be created below.
The fileName is the name of the file, including the file type (like "test.txt").
The contentStream is the stream containing the file content.
The fileBased bool defines if the mediaItem should be stored in the database or in the filesystem.

public static MediaItem CreateMediaItemFromStream(Item parentItem, string fileName, Stream contentStream, bool fileBased)
{
    if (parentItem == null)
    {
        throw new ArgumentNullException("parentItem", "parentItem must not be null.");
    }

    if (string.IsNullOrEmpty(fileName))
    {
        throw new ArgumentException("fileName must not be empty", "fileName");
    }

    // Just in case forwardslash is used, we replace it with backslash, before we do the test.
    string newMediaItemName = fileName.Substring(0, fileName.LastIndexOf('.')).Replace('/', '\\');

    if (newMediaItemName.Contains("\\"))
    {
        // We end here, if the file is uploaded using an ASP.NET FileUpload control, and the IE setting
        // "Include local directory path when uploading files to a server" is enabled.
        // Then we have to remove everything up till the last backslash, to get the filename.
        newMediaItemName = newMediaItemName.Substring(newMediaItemName.LastIndexOf('\\') + 1);
    }

    MediaCreatorOptions md = new MediaCreatorOptions
    {
        Database = DatabaseHelper.MasterDatabase,
        Destination = string.Format("{0}/{1}", parentItem.Paths.FullPath, ItemUtil.ProposeValidItemName(newMediaItemName)),
        FileBased = fileBased,
        IncludeExtensionInItemName = false,
        Versioned = false
    };

    using (new SecurityDisabler())
    {
        return MediaManager.Creator.CreateFromStream(contentStream, fileName, md);
    }
}

This also handles files being uploaded from Internet Explore, when it sends it's entire file path instead of just the file name.

Ingen kommentarer:

Send en kommentar