Home > Net >  Cloudinary download video/audio
Cloudinary download video/audio

Time:04-21

I'm trying to download audio from cloudinary. It's started throw error after i added Transformation in uploadParams. But it's working fine with images. Getting following error:

{
    "innerException": "at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)\r\n   
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)\r\n   at System.Threading.Tasks.Task`1.get_Result()\r\n   
    at gspark.API.Controllers.TracksController.UpdateTrack(DtoUpdateTrack dtoUpdateTrack, Int32 id, IFormFile file) in C:\\Users\\GSpark\\source\\repos\\gspark\\gspark\\Controllers\\TracksController.cs:line 69\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\r\n   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n   
    at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\r\n   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\r\n   
    at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n   
    at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)\r\n   at gspark.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context) in C:\\Users\\GSpark\\source\\repos\\gspark\\gspark\\Middleware\\ExceptionMiddleware.cs:line 24",
    "statusCode": 500,
    "message": "One or more errors occurred. (An error has occured while uploading file (status code: InternalServerError). General Error)"
}
ERROR|gspark.Middleware.ExceptionMiddleware|One or more errors occurred. (An error has occured while uploading file (status code: InternalServerError). General Error) System.Exception: An error has occured while uploading file (status code: InternalServerError). General Error
   at CloudinaryDotNet.Cloudinary.CheckUploadResult[T](T result)
   at CloudinaryDotNet.Cloudinary.UploadLargeAsync[T](BasicRawUploadParams parameters, Int32 bufferSize, Nullable`1 cancellationToken)
   at gspark.Service.Implementation.FileService.AddFileAsync(IFormFile file) in C:\Users\GSpark\source\repos\gspark\gspark.Service\Implementation\FileService.cs:line 55|url: http://localhost/api/tracks/edit/12|action: UpdateTrack|gspark.Middleware.ExceptionMiddleware.InvokeAsync| body: 

FileService implementation:

public async Task<VideoUploadResult> AddFileAsync(IFormFile file)
    {
        var uploadResult = new VideoUploadResult();

        if (file.Length > 0)
        {
            using var stream = file.OpenReadStream();
            var uploadParams = new VideoUploadParams()
            {
                File = new FileDescription(file.Name, stream),
                Transformation = new Transformation().Flags($"attachment:{file.Name}")
            };
   ERROR -> uploadResult = await _cloudinary.UploadLargeAsync(uploadParams);
        }

        return uploadResult;
    }

My controller:

[HttpPut("edit/{id}")]
    public async Task<IActionResult> UpdateTrack([ModelBinder(BinderType = typeof(JsonModelBinder))] DtoUpdateTrack dtoUpdateTrack,
        int id, IFormFile file)
    {
        var user = await _unitOfWork.UserRepository.GetUserByName(User.FindFirstValue(ClaimTypes.GivenName));
        var track = await _unitOfWork.Repository<Track>().GetByIdAsync(id);
        
        var result = _fileService.AddFileAsync(file);
ERROR ->if (result.Result.Error != null)
        {
            _logger.LogError(result.Result.Error.Message);
            return BadRequest(result.Result.Error.Message);
        }
        
        var resultFile = new File()
        {
            Url = result.Result.Url.AbsoluteUri,
            PublicId = result.Result.PublicId,
            UserId = user.Id
        };
...

If i change file.Name to actual filename im getting this error:

One or more errors occurred. (An error has occured while uploading file (status code: BadRequest). Transformation Invalid flag in transformation: mp3)"

CodePudding user response:

The fl_attachement would require the name of the file to be downloaded without the extension as described here. The asset has to be uploaded to your Media Library account:

var uploadParams = new VideoUploadParams()
{
    File = new FileDescription(file.Name, stream)
};

And then, using the public_id, you can build the delivery URL. For example:

var deliveryUrl = cloudinary.Api.UrlVideoUp.Transform(new Transformation().Flags($"attachment:audio").FetchFormat("mp3")).BuildUrl("audio.mp3");
  • Related