How to upload image to server from xamarin forms app?

DMartDMart USMember ✭✭
edited April 2018 in Xamarin.Forms

I'm trying to send an image from my xamarin forms application to a asp .net core server using a post request. I need to save the image in some server folder but I can not do it.

This is the method to send the image once I have it selected in _mediaFile

    private async void UploadFile_Clicked(object sender, EventArgs e)
    {
        var uri = new Uri(string.Format(Constants.UsersRestUrl + "/Files/Upload/", string.Empty));
        var content = new MultipartFormDataContent();

        content.Add(new StreamContent(_mediaFile.GetStream()),
            "\"file\"",
            $"\"{_mediaFile.Path}\"");

        var httpClient = new HttpClient();
        var httpResponseMessage = await httpClient.PostAsync(uri, content);
    }

I currently have this in my api controller

[Route("Files/Upload/")]
[HttpPost]
public async Task<IActionResult> Post(IFormFile file)
{
    Debug.Write("******");
    // full path to file in temp location
    var filePath = Path.GetTempFileName();
    Debug.Write("****** File Path " + filePath);

    if (file.Length > 0)
    {
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
    }
    return Ok(new { file });
}

Can someone help me? Thanks

Best Answer

  • DMartDMart US ✭✭
    edited April 2018 Accepted Answer

    In the end I got it! What I needed was to send an image and save it to a server inside wwwroot folder. I leave here the method for server controller in case someone needs it in the future.

    [Route("Files/Upload/")]
    [HttpPost]
    public async Task<IActionResult> Post(IFormFile file)
    {
        //Windows path
        var uploadLocation = Path.Combine(_env.WebRootPath, "Uploads\\UsersImg");
    
        //Linux path
        //var uploadLocation = Path.Combine(_env.WebRootPath, "Uploads//UsersImg");
    
        var fileName = file.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
    
        if (file.Length > 0)
            {
                using (var stream = new FileStream(Path.Combine(uploadLocation, fileName), FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
        return Ok();
    }
    

    The image is saved in /Uploads/UsersImg/ folder inside wwwroot folder. The method to send the image from client to server it's the same I posted in the question.

Answers

  • MANIKANTA_GMANIKANTA_G INMember ✭✭

    Try to convert image into Base64 and then pass Base64 object into server. In the same way take Base64 object fro the server whereever you need and than reconvert into image and dispaly.

  • DMartDMart USMember ✭✭
    edited April 2018 Accepted Answer

    In the end I got it! What I needed was to send an image and save it to a server inside wwwroot folder. I leave here the method for server controller in case someone needs it in the future.

    [Route("Files/Upload/")]
    [HttpPost]
    public async Task<IActionResult> Post(IFormFile file)
    {
        //Windows path
        var uploadLocation = Path.Combine(_env.WebRootPath, "Uploads\\UsersImg");
    
        //Linux path
        //var uploadLocation = Path.Combine(_env.WebRootPath, "Uploads//UsersImg");
    
        var fileName = file.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
    
        if (file.Length > 0)
            {
                using (var stream = new FileStream(Path.Combine(uploadLocation, fileName), FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
        return Ok();
    }
    

    The image is saved in /Uploads/UsersImg/ folder inside wwwroot folder. The method to send the image from client to server it's the same I posted in the question.

  • JeffLimJeffLim USMember ✭✭

    Hi,

    I got it work as well. My images are saved in wwwroot/uploads folder.
    Because I save it to:
    'var uploadLocation = Path.Combine(_env.WebRootPath, "uploads");

    However, I couldn't browse the image from the browser?
    I was trying it with:
    https://localhost:5001/wwwroot/uploads/IMG_20181005_110900.JPG
    But nothing come out. No error at all. Just a blank page. I am sure the image is exist in the folder.
    Unless it's down to permission issue.

    @DMart Do you have the same issue?

  • JeffLimJeffLim USMember ✭✭

    OK,. I got it work. after I add this line to my Startup.cs
    app.UseStaticFiles();
    :)
    Ref: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.1&tabs=aspnetcore2x

Sign In or Register to comment.