Sep 20, 2019

Upload file to Console Webapi (Owin)

Upload a file to a console based webapi host (owin).

Method 1: MultipartFormDataStreamProvider

 

[HttpPost]
public async Task PostFile()
{
 string root = AppDomain.CurrentDomain.BaseDirectory + "Uploads"; 

 var provider = new MultipartFormDataStreamProvider(root);
 await Request.Content.ReadAsMultipartAsync(provider);
 foreach (var file in provider.FileData)
 {
  var buffer = File.ReadAllBytes(file.LocalFileName);  
 }
 return new HttpResponseMessage() { Content = new StringContent("OK") };
}

Postman Post Sample

Select form-data for Body. Enter key name and select a file for the value.
POST /api/file/PostByteArrayAsync HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Length: 15143
Connection: keep-alive
cache-control: no-cache


Content-Disposition: form-data; name="file"; filename="/C:/Users/oktay/logs.txt


------WebKitFormBoundary7MA4YWxkTrZu0gW--

Method 2: ReadAsByteArrayAsync

This method requires filename in header. Add key/value for "filename".
 

[HttpPost]
public string PostFile()
{
 string fileName = Request.Headers.GetValues("filename").ElementAt(0);

 string root = AppDomain.CurrentDomain.BaseDirectory + "Uploads\\";
 var filePath = root + fileName;

 var fc = Request.Content.ReadAsByteArrayAsync().Result;
 File.WriteAllBytes(filePath, fc);

 return "uploaded";
}