I want to post a file to a web server that will validate and return another file after validation.
This is from the server:
[HttpPost("UploadFile")]
[Route("test")]
public FileInformation CreateGame([FromForm] FileInformation fileInformation)
{
FileInformation f = new FileInformation();
f.Name = fileInformation.Name;
f.Description = fileInformation.Description;
f.File = fileInformation.File; // the console cannot convert this
//System.IO.File.WriteAllBytes("wwwroot\", fileInformation.File);
try
{
using (Stream fileStream = new FileStream("wwwroot\" + fileInformation.Name, FileMode.Create))
{
fileInformation.File.CopyToAsync(fileStream);
}
}
catch { }
return fileInformation;
}
public class FileInformation
{
public string Name { get; set; }
public string Description { get; set; }
public IFormFile File { get; set; }
}
This part is from the console application
string filePath = @"TextFile1.txt";
using var form = new MultipartFormDataContent();
using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "File", Path.GetFileName(filePath));
form.Add(new StringContent("TextFile1.txt"), "Name");
form.Add(new StringContent("TextFile1.txt"), "Description");
var httpClient = new HttpClient()
{
BaseAddress = new Uri("https://localhost:7009")
};
var response = await httpClient.PostAsync($"/api/UploadScore/test", form);
//response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
FileInformation f = JsonConvert.DeserializeObject<FileInformation>(responseContent);
If I populate the File
property in fileInformation
, the code crashes upon conversion. I can’t figure this out.
I have tried to convert using ReadAsArray.
I want to be able to retrieve a file from the server.
3