@using System.Net
@using Umbraco.Cms.Core
@using Umbraco.Cms.Core.Services
@using Umbraco.Cms.Core.PropertyEditors
@using Umbraco.Cms.Core.IO
@using Umbraco.Cms.Core.Serialization
@using Umbraco.Cms.Core.Strings
@inject MediaFileManager MediaFileManager
@inject IShortStringHelper ShortStringHelper
@inject IContentTypeBaseServiceProvider ContentTypeBaseServiceProvider
@inject IContentService ContentService
@inject IMediaService MediaService
@inject IJsonSerializer Serializer
@inject MediaUrlGeneratorCollection MediaUrlGeneratorCollection
@{
// Create a variable for the GUID of the parent where you want to add a child item
var guid = Guid.Parse("32e60db4-1283-4caa-9645-f2153f9888ef");
// Get the page using the GUID you've defined
var content = ContentService.GetById(guid); // ID of your page
// Create a variable for the file you want to upload, in this case the Our Umbraco logo
var imageUrl = "https://our.umbraco.com/assets/images/logo.svg";
// Create a request to get the file
var request = WebRequest.Create(imageUrl);
var webResponse = request.GetResponse();
var responseStream = webResponse.GetResponseStream();
// Get the file name
var lastIndex = imageUrl.LastIndexOf("/", StringComparison.Ordinal) + 1;
var filename = imageUrl.Substring(lastIndex, imageUrl.Length - lastIndex);
// Create a media file
var media = MediaService.CreateMediaWithIdentity("myImage", -1, "File");
media.SetValue(MediaFileManager, MediaUrlGeneratorCollection, ShortStringHelper, ContentTypeBaseServiceProvider, Constants.Conventions.Media.File, filename, responseStream);
// Save the created media
MediaService.Save(media);
// Get the published version of the media (IPublishedContent)
var publishedMedia = Umbraco.Media(media.Id);
// Set the value of the property with alias 'myFile'
content.SetValue("myFile", publishedMedia.Url());
// Save the child item
ContentService.Save(content);
}