Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Abdul Rahim 14 posts 84 karma points
    Feb 27, 2019 @ 14:36
    Abdul Rahim
    0

    Create Media on Azure Blob Storage Using C#

    Hi Guys,

    I am using UmbracoFileSystemProviders.Azure to setup Umbraco media files to use an Azure storage account.

    I have requirement to create media(Image) in azure blob storage using c# code. Here is the code I used before with local file system.

    public int SaveImage(string url, int mediaNodeId)
        {
            try
            {
                var mediaService = Services.MediaService;
                string originalFileName = Path.GetFileName(url);
                string filenameToSave = Path.GetFileNameWithoutExtension(originalFileName) + Guid.NewGuid() + Path.GetExtension(originalFileName);
    
                string imageUrl = url; // Get file URL
                string saveLocation = Server.MapPath("~/Imports/" + filenameToSave); // The file will downloaded into a folder in root
    
                byte[] imageBytes;
                HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
                WebResponse imageResponse = imageRequest.GetResponse();
    
                Stream responseStream = imageResponse.GetResponseStream();
    
                using (BinaryReader br = new BinaryReader(responseStream))
                {
                    imageBytes = br.ReadBytes(500000000);
                    br.Close();
                }
                responseStream.Close();
                imageResponse.Close();
    
                FileStream fs = new FileStream(saveLocation, FileMode.Create);//save the image to the root folder
                BinaryWriter bw = new BinaryWriter(fs);
    
                bw.Write(imageBytes);
    
                var mediaImage = mediaService.CreateMedia(originalFileName, mediaNodeId, "Image");
                mediaImage.SetValue("umbracoFile", originalFileName, fs);//setting filestream to UmbracoFile
                mediaService.Save(mediaImage);//Save media
                fs.Close();
                bw.Close();
                return mediaImage.Id;
    
            }
            catch (Exception ex)
            {
    
            }
            return 0;
        }
    

    The above code is not working when I am trying to create image to Azure blob storage. Please help!

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies