2

I'm trying to post a file + some info to a WebApi I control. My problem is that I can't access the file on the WebAPI side, all other fields are OK.

Here is my Console Application code

using (HttpClient client = new HttpClient()) { using (MultipartFormDataContent content = new MultipartFormDataContent()) { string filename = "my_filename.png"; content.Add(new StringContent(DateTime.Now.ToString("yyyy-MM-dd")), "data"); byte[] file_bytes = webClient.DownloadData($"https://my_url/my_file.png"); content.Add( new ByteArrayContent(file_bytes), "file"); string requestUri = "http://localhost:51114/api/File"; HttpResponseMessage result = client.PostAsync(requestUri, content).Result; Console.WriteLine("Upload result {0}", result.StatusCode); } } 

Here is my WebAPI Code

 [HttpPost] public void Post(IFormFile file, [FromForm] DateTime data) { if (file == null || file.Length == 0) { Response.StatusCode = StatusCodes.Status400BadRequest; return; } // Never reaches this point..... file is null } 

Any pointers on what I might be missing?

2 Answers 2

1

If i'm not mistaken, you can submit a file to a WebAPI endpoint sending it as FormData with a Content-Type : multipart/form-data, something like this.

[HttpPost] [Route("..."] public void ReceiveFile() { System.Web.HttpPostedFile file = HttpContext.Current.Request.Files["keyName"]; System.IO.MemoryStream mem = new System.IO.MemoryStream(); file.InputStream.CopyTo(mem); byte[] data = mem.ToArray(); // you can replace the MemoryStream with file.saveAs("path") if you want. } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. +1 but it didn't solve my problem. I think that the issue is with the sending part, because i can use the method good using insomnia.
1

You can grab out the content and convert it into a byte array in 2 lines of code, assuming you are only sending a single file (Note) its a good idea to use async for file upload so you don't consume as much cpu time:

var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()); var file = provider.Contents.Single(); 

1 Comment

Thank you. +1 but it didn't solve my problem. I think that the issue is with the sending part, because i can use the method good using insomnia.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.