REST file upload with HttpRequestMessage or Stream?

前端 未结 2 522
半阙折子戏
半阙折子戏 2020-12-31 09:05

What is the better way to upload a file for a REST client?

From the WCF Web API Documentation

[WebInvoke(UriTemplate = \"thumbnail\", Method = \"POST         


        
相关标签:
2条回答
  • 2020-12-31 09:22

    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.

    0 讨论(0)
  • 2020-12-31 09:37

    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.

    0 讨论(0)
提交回复
热议问题