Copied to clipboard

Flag this post as spam?

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


  • Sanjay 4 posts 74 karma points
    6 days ago
    Sanjay
    0

    Image upload to Media folder in .net core api

    Hello Team,

    I am trying to upload the image to media folder under a folder which we are receiving the file from frontend in .net core api. I am using Umbraco 3.2.2 version.

    When I am trying like below its throwing that file container is not exists:

    [HttpPost("/agents/logo-upload")]
    public async Task<IActionResult> UploadImage([FromForm]IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return BadRequest("No file uploaded.");
        }
    
        try
        {
            // 1. Generate a unique file name and save it to the media folder
            var folderName = _authenticationService.GetAgent().Agency.Name;
            folderName = folderName.Trim().Replace(" ","").ToLower();
    
            var fileName = Path.GetFileName(file.FileName);
            var filePath = Path.Combine("media", folderName, fileName);  // Replace with your media folder path
    
    
            var existingFolder = _mediaService.GetRootMedia().FirstOrDefault(m => m.Name.InvariantEquals(folderName));
            if (existingFolder == null)
            {
                var newFolder = _mediaService.CreateMedia(folderName, Constants.System.Root, "Folder");
                _mediaService.Save(newFolder);
                existingFolder = newFolder;
            }
    
            var directoryPath = Path.GetDirectoryName(filePath);
    
    
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            IMedia media = null;
            using (var stream = System.IO.File.OpenRead(filePath))
            {
                media = _mediaService.CreateMedia(fileName, existingFolder.Id, Constants.Conventions.MediaTypes.Image);
    
                media.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, fileName, stream);
                _mediaService.Save(media); // throwing the error here
            }
    
    
    
    
    
    
            return Ok(new { MediaId = media.Id, FilePath = filePath });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error while uploading image.");
            return StatusCode(500, "Internal server error");
        }
    }
    
    }
    

    Is it not possible to upload the image to Umrbaco backoffice media folder?

    enter image description here

  • Afreed 47 posts 213 karma points
    5 days ago
    Afreed
    0

    Hi Sanjay,

    Are you hosted on Azure? If so, you don't need to save the image to a directory unless it's absolutely necessary. You can directly use the file stream to create the media item in Umbraco like this:

    using (var stream = file.OpenReadStream())
            {
                var media = _mediaService.CreateMedia(file.FileName, folderName, Constants.Conventions.MediaTypes.Image);
                media.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, file.FileName, stream);
                _mediaService.Save(media);
            }
    

    If not, you might want to check into storage account configuration

  • Sanjay 4 posts 74 karma points
    5 days ago
    Sanjay
    0

    I have tried like above without storing the file anywhere. But still it throws same error.

  • Afreed 47 posts 213 karma points
    5 days ago
    Afreed
    0

    It's working fine for me maybe you got something wrong with the controller

    using Microsoft.AspNetCore.Mvc;
    using Umbraco.Cms.Core;
    using Umbraco.Cms.Core.IO;
    using Umbraco.Cms.Core.Models;
    using Umbraco.Cms.Core.PropertyEditors;
    using Umbraco.Cms.Core.Services;
    using Umbraco.Cms.Core.Strings;
    using Umbraco.Extensions;
    
    namespace Test.Web
    {
        [ApiController]
        public class TestController : ControllerBase
        {
            private readonly IMediaService _mediaService;
            private readonly IContentTypeBaseServiceProvider _contentTypeBaseServiceProvider;
            private readonly IShortStringHelper _shortStringHelper;
            private readonly MediaUrlGeneratorCollection _mediaUrlGeneratorCollection;
            private readonly MediaFileManager _mediaFileManager;
    
            public TestController(IMediaService mediaService, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, MediaFileManager mediaFileManager, IShortStringHelper shortStringHelper, MediaUrlGeneratorCollection mediaUrlGenerators) {
                _mediaService = mediaService;
                _contentTypeBaseServiceProvider = contentTypeBaseServiceProvider;
                _shortStringHelper = shortStringHelper;
                _mediaUrlGeneratorCollection = mediaUrlGenerators;
                _mediaFileManager = mediaFileManager;
            }
    
            [HttpPost("/agents/logo-upload")]
            public async Task<IActionResult> UploadImage([FromForm] IFormFile file)
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest("No file uploaded.");
                }
    
                try
                {
                    // 1. Generate a unique file name and save it to the media folder
                    var folderName ="test";
                    folderName = folderName.Trim().Replace(" ", "").ToLower();
    
                    var fileName = Path.GetFileName(file.FileName);
                    var filePath = Path.Combine("media", folderName, fileName);  // Replace with your media folder path
    
    
                    var existingFolder = _mediaService.GetRootMedia().FirstOrDefault(m => m.Name.InvariantEquals(folderName));
                    if (existingFolder == null)
                    {
                        var newFolder = _mediaService.CreateMedia(folderName, Constants.System.Root, "Folder");
                        _mediaService.Save(newFolder);
                        existingFolder = newFolder;
                    }
    
                    IMedia media = null;
                    using (var stream = file.OpenReadStream())
                    {
                        media = _mediaService.CreateMedia(file.FileName, existingFolder.Id, Constants.Conventions.MediaTypes.Image);
                        media.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, file.FileName, stream);
                        _mediaService.Save(media);
                    }
    
                    return Ok(new { MediaId = media.Id, FilePath = filePath });
                }
                catch (Exception ex)
                {
                    return StatusCode(500, "Internal server error");
                }
            }
    
        }
    }
    
  • Sanjay 4 posts 74 karma points
    5 days ago
    Sanjay
    0

    oh okay. is there any setting that I have to change?

    I am trying to upload locally in back office media folder manually, still its throws below error:

    Azure.RequestFailedException: The specified container does not exist.
    RequestId:e1f6c584-3bc6-4cea-bbe5-c6718ea13d8f
    Time:2024-11-27T10:47:05.212Z
    Status: 404 (The specified container does not exist.)
    ErrorCode: ContainerNotFound
    
  • Afreed 47 posts 213 karma points
    5 days ago
    Afreed
    0

    could you removing the blob storage config and try again? (Umbraco is attempting to access an Azure Blob Storage container to upload or retrieve media files).

  • Sanjay 4 posts 74 karma points
    5 days ago
    Sanjay
    0

    It is resolved by creating media folder in local azure blob storage. Thought it will automatically created, but its actually not.

Please Sign in or register to post replies

Write your reply to:

Draft