How to upload images progammatically for a page?

Vote:
 

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

#150324
Jun 16, 2016 9:14
Vote:
 

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

#150326
Jun 16, 2016 10:12
Vote:
 

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;
}
#150329
Jun 16, 2016 11:17
Vote:
 

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.

#150339
Jun 16, 2016 12:52
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.