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?