November Happy Hour will be moved to Thursday December 5th.
AI OnAI Off
November Happy Hour will be moved to Thursday December 5th.
Hi,
Step 1 :
Upload a media file e.g.
var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>(); var blobFactory = ServiceLocator.Current.GetInstance<BlobFactory>(); //Get a new empty file data var file1 = contentRepository.GetDefault<GenericFile>(SiteDefinition.Current.GlobalAssetsRoot); file1.Name = "Readme.txt"; //Create a blob in the binary container var blob = blobFactory.CreateBlob(file1.BinaryDataContainer, ".txt"); using (var s = blob.OpenWrite()) { StreamWriter w = new StreamWriter(s); w.WriteLine("Hello world"); w.Flush(); } //Assign to file and publish changes file1.BinaryData = blob; var file1ID = contentRepository.Save(file1, SaveAction.Publish);
Step 2: Associate that Media with some property of page and publish
//Get Media Item
/Get Page
// Assign media to property of required page
//Publish page
Regards
/K
Here is a method for downloading an image from url and then uploading it to episerver in "for this page"-folder:
var imageRef = DownloadAndUploadImageFromUrl(url, "test", ".jpg", currentPage.ContentLink) private ContentReference DownloadAndUploadImageFromUrl(string url, string fileName, string fileExtension, ContentReference imageFolderReference) { var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>(); var blobFactory = ServiceLocator.Current.GetInstance<BlobFactory>(); var contentAssetHelper = ServiceLocator.Current.GetInstance<ContentAssetHelper>(); Byte[] data = null; using (var webClient = new WebClient()) { data = webClient.DownloadData(url); } var imageFile = contentRepository.GetDefault<ImageFile>(contentAssetHelper.GetOrCreateAssetFolder(imageFolderReference).ContentLink); imageFile.Name = fileName; var blob = blobFactory.CreateBlob(imageFile.BinaryDataContainer, fileExtension); using (var s = blob.OpenWrite()) { var w = new StreamWriter(s); w.BaseStream.Write(data, 0, data.Length); w.Flush(); } imageFile.BinaryData = blob; var imageContentRef = contentRepository.Save(imageFile, SaveAction.Publish); return imageContentRef; }
Tim Røgler has correct guide for your question, the main requirement here is uploading images into the "For this page" folder, so that you need to figure out where it is by using contentAssetHelper.GetOrCreateAssetFolder and passed the Page/Block's contentLink.
How to upload images for a page programmatically? After publish images should be visible under "For this page" section and not in any folder under Media