REST file upload with HttpRequestMessage or Stream?

前端 未结 2 547
半阙折子戏
半阙折子戏 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: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.

提交回复
热议问题