Forum Xamarin.Forms

(Exception :Could not find a part of the path) when trying to upload file to server

OmarMohOmarMoh USMember ✭✭

Hi Xamarin Developers

I'm trying to upload image files that required to my xamarin.forms project using 'IFormFile interface' inside web api service project, I tested the web service using Postman and it's works successfully, As the title said , The exception occurs as returned message from server when post file from xamarin.forms app.
please checkout the attached photos and my code and thanks for all

Back end both model & controller

public class FIleUploadAPI { public IFormFile files { get; set; } }

` public class ProductImageUploadController : ControllerBase
{
public static IHostingEnvironment _environment;

    public ProductImageUploadController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    [HttpPost]
    public async Task<string> Post(FIleUploadAPI files)
    {
        string[] _extentions = { "image/jpg", "image/png", "image/jpeg" };
        var _json = "";
        if (files.files.Length > 0)
        {
            // if(files.files.ContentType == _extentions[0] || files.files.ContentType == _extentions[1] || files.files.ContentType == _extentions[2])
            // {
            try
            {
                    if (!Directory.Exists(_environment.WebRootPath + "/Productuploads/"))
                    {
                        Directory.CreateDirectory(_environment.WebRootPath + "/Productuploads/");
                    }
                    using (FileStream filestream = System.IO.File.Create(_environment.WebRootPath + "/Productuploads/" + files.files.FileName))
                    {
                        files.files.CopyTo(filestream);
                        filestream.Flush();
                        //  return _json = JsonConvert.SerializeObject("Profile updated");
                        return _json = JsonConvert.SerializeObject(_environment.WebRootPath + "/Productuploads/" + files.files.FileName);
                    }
                }
                catch (Exception ex)
                {
                    return _json = JsonConvert.SerializeObject("File_Name*_*:"+ files.files.FileName + "Error*_*: "+ ex.ToString());
                }
          //  }
          //  else
           // {
             //   _json = JsonConvert.SerializeObject("Incurrect image type");
              //  return _json;

            //}
        }
        else
        {
            _json = JsonConvert.SerializeObject("Faild to upload image");
            return _json;
        }

    }
}

}`

Front end

`public async void UploadImageAsync(Stream image, string name)
{
var _index = name.IndexOf("p/");
var _str = name.Substring(_index + 2);
await DisplayAlert("Message", _str, "Ok");

        RestAPI _rest = new RestAPI
        {
            Url = "https://xxx/api/ProductImageUpload"
        };


        HttpClient httpClient = new HttpClient();
        HttpContent fileStreamContent = new StreamContent(image);
        fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "files", FileName = name};
        fileStreamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(fileStreamContent);
            try
            {
                httpClient.BaseAddress = new Uri(_rest.Url);
                var response = await httpClient.PostAsync("", formData);
                var _resultContent = await response.Content.ReadAsStringAsync();
                var _result = JsonConvert.DeserializeObject<string>(_resultContent);
                await DisplayAlert("Message", _result, "Ok");
            }
            catch (Exception e)
            {
                await DisplayAlert("Message", e.ToString(), "Ok");
            }
        }
    }`




Best Answer

  • OmarMohOmarMoh US ✭✭
    Accepted Answer

    I solved the problem, in my case the content key in front end was different from Model class in back end that received the file. i used MultipartFormDataContent

Answers

  • XamtasticXamtastic Member ✭✭✭
    edited September 2019

    I'm glad I looped back on this...

    I think what you want is Xam.Plugin.Media to handle your file selection, then from there use the bytes to send to API via your json (model {filename:string,filedata:byte[]}). Based on your error and Front end.

  • OmarMohOmarMoh USMember ✭✭
    edited September 2019

    @Xamtastic Thanks for replying, Could you write the back end code ?

  • XamtasticXamtastic Member ✭✭✭

    It's on their GitHub...............
    https://github.com/jamesmontemagno/MediaPlugin

  • OmarMohOmarMoh USMember ✭✭

    I appreciate your reply but, you said use the byte to send file via json format so , i'm asking for backend code that means Wep api code, the image stream file was converted to byte[] as you said but how web api can store the byte[] ?

  • XamtasticXamtastic Member ✭✭✭

    Step 1:

    For the API, there are literally hundreds if not thousands of code snippets out there for C#. Grab one and get it working - demonstrate communication with your server using a simple model sent as a JSON script.

    Step 2:
    Send the object.

        public class MyFileModel {
            public string FileName {get;set;}
            public byte[] FileData {get;set;}
        }
    
        void SubmitFile()
        {
            //  ....get code from GIT ---> See "Usage" 
    
            var m = new MyFileModel()
            {
                FileName = plugin.FileName,
                FileData = File.ReadAllBytes(plugin.Data)
            };
    
            var json = JsonConvert.SerializeObject(m);
    
            YourApiService.Send(json);
        }
    
  • OmarMohOmarMoh USMember ✭✭
    Accepted Answer

    I solved the problem, in my case the content key in front end was different from Model class in back end that received the file. i used MultipartFormDataContent

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    If you solved this issue by yourself, please mark your reply as answer, it will help others who have similar issue.

Sign In or Register to comment.