What is the better way to upload a file for a REST client?
From the WCF Web API Documentation
[WebInvoke(UriTemplate = "thumbnail", Method = "POST")]
public HttpResponseMessage UploadFile(HttpRequestMessage request)
{
From multiple forum posts:
WCF REST File upload with additional parameters
[WebGet(UriTemplate="", Method ="POST"]
public string UploadFile(Stream fileContents)
I understand, that the first method allows to directly post a file from a normal HTML form. The 2nd approach seems more common on all forum posts I find.
What would you recommend and why? The REST api should be accessible from all kind of languages and platforms.
For the HttpRequestMessage approach, how would I do an upload a file preferable with the WCF HttpClient? With the FormUrlEncodedMediaTypeFormatter)
In order to test the HttpRequestMessage approach I have done the following using MVC:
public class TestingController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Upload()
{
var file = Request.Files[0];
var filename = Request.Form["filename"];
var uri = string.Format("http://yoururl/serviceRoute/{0}", filename);
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/pjpeg"));
var content = new StreamContent(file.InputStream);
var response = client.PostAsync(uri, content);
ViewBag.ServerUri = uri;
ViewBag.StatusCode = response.Result.StatusCode.ToString();
return View();
}
}
The Index view should have a form in it that posts back to the Upload method. Then you are able to use the HttpClient to make a connection to your REST service.
The first method is "closer to the metal" and would be more flexible since you would be processing the http requests and building the responses yourself. If all you need to do is accept a stream from a client, the second option is much simpler from the implementation standpoint (under the hood, it does the same work that the first method is doing)
I don't have an answer for your last question.
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