I have created an API which takes a file as input and processes it. The sample is like this...
[HttpPost]
public string ProfileImagePost(HttpPostedFile HttpFile)
{
//rest of the code
}
Then I have creted a Client to consume this as follows...
string path = @"abc.csv";
FileStream rdr = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] inData = new byte[rdr.Length];
rdr.Read(inData, 0, Convert.ToInt32(rdr.Length));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/abc/../ProfileImagePost");
req.KeepAlive = false;
req.ContentType = "multipart/form-data";
req.Method = "POST";
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
reqStream.Write(inData, 0, Convert.ToInt32(rdr.Length));
reqStream.Close();
HttpWebResponse TheResponse = (HttpWebResponse)req.GetResponse();
string TheResponseString1 = new StreamReader(TheResponse.GetResponseStream(), Encoding.ASCII).ReadToEnd();
TheResponse.Close();
But I get 500 error at on client side. Help me out of it guys.
Thanx in advance...
The ASP.NET Web API doesn't work with HttpPostedFile. Instead you should use a MultipartFormDataStreamProvider as shown in the following tutorial.
Also your client side call is wrong. You have set the ContentType to multipart/form-data but you are not respecting this encoding at all. You are simply writing the file to the request stream.
So let's take an example:
public class UploadController : ApiController
{
public Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HostingEnvironment.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data
return Request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
{
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
and then you could use an HttpClient to call this API:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
class Program
{
static void Main(string[] args)
{
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri("http://localhost:16724/");
var fileContent = new ByteArrayContent(File.ReadAllBytes(@"c:\work\foo.txt"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Foo.txt"
};
content.Add(fileContent);
var result = client.PostAsync("/api/upload", content).Result;
Console.WriteLine(result.StatusCode);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With