0

I'm trying to send a file to an existing API I wrote, however when the API receives the file, it null. The API picks up the file at the point of 'request.GetRequestStream()'. The API works with Postman, so I'm pretty sure that the problem is my code. Here it is

public static void SendFile(Stream DATA)
{
    
    try
    {
        
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "multipart/form-data";
        int bytesRead = 0;
        byte[] requestByte = new byte[DATA.Length];
        request.ContentLength = requestByte.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            while ((bytesRead = DATA.Read(requestByte, 0, requestByte.Length)) != 0)
            {
                requestStream.Write(requestByte, 0, bytesRead);
                requestStream.Close();
            }
        }
        WebResponse webResponse = request.GetResponse();
        Stream webStream = webResponse.GetResponseStream();
        StreamReader responseReader = new StreamReader(webStream);
        string response = responseReader.ReadToEnd();
        Console.Out.WriteLine(response);
        responseReader.Close();
    }
    catch (Exception e)
    {
        Console.Out.WriteLine("-----------------");
        Console.Out.WriteLine(e.Message);
    }

}

The API is as follows

[HttpPost("upload")]
        public IActionResult UploadFile([FromForm(Name = "files")] List<IFormFile> files)
        {
            string subDirectory = "reports";
            try
            {
                if (files != null)
                {
                    _fileService.SaveFile(files, subDirectory);
                    _fileService.ProcessFiles(files);
                    return Ok(new { files.Count, Size = FileService.SizeConverter(files.Sum(f => f.Length)) });
                }
                else
                    return Ok("Upload failed");
            }
            catch (Exception exception)
            {
                return BadRequest($"Error: {exception.Message}");
            }
        }

Where URL is the location of the API (both of them running on the same PC right now).

What am I doing wrong?

TheWizardOfTN
  • 161
  • 10
  • Can you share the api implementation or the postman request – Gal I. Sep 28 '21 at 17:57
  • Notice the remark in the [documentation about HttpWebRequest](https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?view=net-5.0): *We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class* – Xerillio Sep 28 '21 at 17:58
  • requestStream.Close(); doesn't seem right. I believe your using statement will auto-dispose, so it's not necessary even after that while loop. – pcalkins Sep 28 '21 at 18:00
  • I added the API code per Gal;s request – TheWizardOfTN Sep 28 '21 at 18:01
  • @pcalkins - it has already failed by that part of the code – TheWizardOfTN Sep 28 '21 at 18:02
  • Looks like you simply send the bytes of your file as request body. This will not work if form data encoded data is expected. Here's an example that uses the current HttpClient: https://stackoverflow.com/questions/42212406/how-to-send-a-file-and-form-data-with-httpclient-in-c-sharp – Christoph Lütjen Sep 28 '21 at 18:06
  • You use ```multipart/form-data``` content to send your files. It's not the same as just dump the content of your file inside the POST body. Use ```HttpClient``` and ```MultipartFormDataContent```. – Morse Sep 29 '21 at 10:44
  • Thank you for all of these comments, however none of them have worked. It seems like the web page connects to the API and then is waiting for a result instead of sending its data. – TheWizardOfTN Sep 29 '21 at 17:10
  • Can [this answer](https://stackoverflow.com/a/19664927) help you? According to what you said above, it seems that the api worked well as via postman it can receive file. Hence, it may related to the send file method. And I saw that you used `HttpWebRequest` . So I find an answer about it. – Tiny Wang Oct 01 '21 at 04:24
  • @TinyWang - thank you for posting that - no. same result. It's really frustrating – TheWizardOfTN Oct 01 '21 at 18:33
  • I just remembered that maybe cors issue? Does the two projects have different port or they are in the same project? – Tiny Wang Oct 07 '21 at 02:38
  • Different projects - think it might work if I post the API to a web location rather than the same PC? – TheWizardOfTN Oct 12 '21 at 14:31

0 Answers0