Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST file upload with HttpRequestMessage or Stream?

Tags:

c#

asp.net

wcf

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)

like image 873
Remy Avatar asked Feb 15 '12 08:02

Remy


2 Answers

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.

like image 72
Jed Avatar answered Oct 23 '22 14:10

Jed


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.

like image 32
JCaffeine Avatar answered Oct 23 '22 15:10

JCaffeine