Search code examples
asp.net-corefile-uploadblazor-webassembly

Upload FIle In Blazor WebAssembly hosted by aspnetcore


I tried to upload an image in Blazor wasm. It hasn't any error, but the file didn't upload to wwwroot/images directory,

The code I use for upload is here:

byte[] ImageUploaded ; // I have got bytes of file by a code before.
if (ImageUploaded != null)
{
     string path = "~/images";
     if (!Directory.Exists(path)) Directory.CreateDirectory(path);
     path = Path.Combine(path, Guid.NewGuid().ToString() + Path.GetExtension(fileName));
     await System.IO.File.WriteAllBytesAsync(path, ImageUploaded);
}

Can you resolve this problem?

I have searched the web and this site, But I haven't found any results.


Solution

  • Because My Project is a BlazorWebAssembly hosted by AspnetCore (See Image here) then, I uploaded the file in server side (api controller):

        private async Task<IActionResult> FileUpload(AppUser user)
    {
        var path = Directory.GetCurrentDirectory();
        path = Path.Combine(path, @"../Client/wwwroot/images");
        if (Directory.Exists(path) == false) Directory.CreateDirectory(path);
        path = Path.Combine(path, user.ImageName);
        if (user.UserImage != null)
        {
            try
            {
                await System.IO.File.WriteAllBytesAsync(path, user.UserImage);
                return Ok("Succeded");
    
    
            }
            catch (Exception ex)
            {
    
                return NotFound(ex.Message);
            }
        }
            return null;
    
    }
    

    AppUser is a class that contains two property related to Image: public byte[] UserImage {get;set;} public string UserImage {get;set;}

    It's working correctly, But you may suggest better solutions.