EPiServer: How to upload a file to the pagefiles folder

Here's a function to save an uploaded file into an EPiServer page virtual pagefile folder. You might want to check that your UploadFile-control has a file before calling this function (using the HasFile-property on the control).

/// <summary>
/// Save an uploaded file into the virtual pagefiles folder for an EPiServer page
/// </summary>
/// <param name="fileUpload">The FileUpload-controller that is used to upload the file</param>
/// <param name="page">The page for which you want to save the file to</param>
/// <returns>Path to the uploaded file</returns>
private string SaveFile(FileUpload fileUpload, PageData page) {
//Get the page folder ID
int folderId = (int)page.Property["PageFolderID"].Value;

//Get the root directory for page folders
string pageDirectoryRootVirtualPath = VirtualPathHandler.PageDirectoryRootVirtualPath;

VersioningDirectory pageRootDirectory = (VersioningDirectory)GenericHostingEnvironment.VirtualPathProvider.GetDirectory(pageDirectoryRootVirtualPath);

//Combine the root path with folder name and get directory
string virtualPathFromFolderId = VirtualPathUtilityEx.Combine(pageDirectoryRootVirtualPath, VirtualPathUtility.AppendTrailingSlash(folderId.ToString()));

UnifiedDirectory pageDirectory = HostingEnvironment.VirtualPathProvider.GetDirectory(virtualPathFromFolderId) as UnifiedDirectory;

//Bypass security and Create page folder if needed
if (pageDirectory == null) {
pageRootDirectory.BypassAccessCheck = true;
pageDirectory = pageRootDirectory.CreateSubdirectory(folderId.ToString(), page);
}

// Get the filename from the upload control
string fileName = fileUpload.FileName;

// Create a file handle
UnifiedFile file = pageDirectory.CreateFile(fileName);

// Save the content
using (Stream stream = file.Open(FileMode.Create, FileAccess.Write)) {
stream.Write(fileUpload.FileBytes, 0, fileUpload.FileBytes.Length);
}

// Return the path to the uploaded file
return VirtualPathUtilityEx.Combine(pageDirectory.VirtualPath, fileName); ;
}

Thanks goes to Fredrik Haglund for the great information about how to create the pagefiles folder from code.

Related posts:

Comments

comments powered by Disqus