0

I am struggling with uploading an image from thew client-side to a folder on the server-side in .Net Core.I used Postman to check if the method on the server-side is working and it does without any problem,but when I try to upload an image from the client-side,I get an error on the server-side of type NullReferenceException:Object reference not set to an instance of an object.This is the Post method on the server-side:

 [HttpPost]
    public async Task Post(IFormFile file)
    {
       
        if (string.IsNullOrWhiteSpace(_environment.WebRootPath))
         {
             _environment.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
         }
 
         var uploads = Path.Combine(_environment.WebRootPath, "uploads");
         //var fileName = file.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
         if (!Directory.Exists(uploads)) Directory.CreateDirectory(uploads);
         if (file.Length > 0)
         {
             using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
             {
                 await file.CopyToAsync(fileStream);


             }
         }
       
   
    }

Apparently the method is thrown where I check if the length of the file is bigger than 0.On the client-side I get error "500 internal server error" and I tried to check using the debugger where exactly the error is thrown but i can't find anything that could resemble an error of some sort.This is the API method for the client-side:

  public async Task UploadPictureAsync(MediaFile image)
    {
        User user = new User();
        string pictureUrl = "http://10.0.2.2:5000/api/UploadPicture";
        HttpContent fileStreamContent = new StreamContent(image.GetStream());
    //  user.Picture=GetImageStreamAsBytes(image.GetStream());
        fileStreamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {FileName=Guid.NewGuid() + ".Png",Name="image"};
        fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        HttpClientHandler clientHandler = new HttpClientHandler();
        clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
        using (var client = new HttpClient(clientHandler))
        { 
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(fileStreamContent);
                var response = await client.PostAsync(pictureUrl, formData);
               if(response.IsSuccessStatusCode)
                {
                    var result = response.Content.ReadAsStringAsync().Result;
                  
                }
            }
        }
    }

The image is declared in the Model as byte array:

 public byte[] Picture { get; set; }

Does someone understand why my POST method has this behavior since the server-side works perfectly but fails when I try to upload an image from the client-side?What I find weird though is that when i read the error and I look at the Content-Type it is "text/plain" instead of "form-data" and I have tried to set it at the MutipartFormDataContent like this:

formData.Headers.ContentType.MediaType = "multipart/form-data"; 

I also tried to set the MediaTypeHeaderValue on the client like this:

 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));

I still get the wrong content type. I have also tried a different approach with Stream instead of MediaFile but without any luck as it did not even hit the break point in debugger mode for the response.Any help would be appreciated! :)

5
  • 500 is a server error. You need to look at your server logs to see what they can tell you. Commented Aug 5, 2020 at 17:54
  • @Jason Thank you for the reply.The problem is that without trying to upload an image from the client-side,the server-side works perfectly as I tried it with Postman so I believe the problem is on the client-side.When i try to upload from the client-side the error it's thrown along with "System.NullReferenceException: Object reference not set to an instance of an object." on 'file.Length >0'.Why would it work separately but throw a server error when it's used along with the client-side? Commented Aug 5, 2020 at 18:03
  • You may be doing something wrong on the client to cause the problem on the server, but you need to start by figuring out the cause of the 500. Either do that by looking at the logs, or if you are running your server locally, debug it as it receives a request from the client. Commented Aug 5, 2020 at 18:06
  • @Jason thank you for the advice.I will try to figure out the cause of the error and I'll post an answer if I manage to make it work.Best regards! :) Commented Aug 5, 2020 at 18:11
  • I'll not that anything that goes wrong in your server code will cause a 500 because there is no exception handling. Adding some, and some logging, will help you track this down faster. Commented Aug 5, 2020 at 18:13

1 Answer 1

1

I have managed to find the answer finalllyyyyy!!!The problem was on the client-side as I suspected and guess what,it was all about the correct name.It turns out that since on the server side I have IFormFile file I had to change the client side to take the parameter name "file" instead of image as well so that it could work.Thank you @Jason for the suggestions as I didn't understand the error from the first place and did some debugging on the server-side to help me figure it out.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.