【问题标题】:REST file upload with HttpRequestMessage or Stream?使用 HttpRequestMessage 或 Stream 上传 REST 文件?
【发布时间】:2012-03-06 14:45:52
【问题描述】:

为 REST 客户端上传文件的更好方法是什么?

来自 WCF Web API 文档

[WebInvoke(UriTemplate = "thumbnail", Method = "POST")]
public HttpResponseMessage UploadFile(HttpRequestMessage request)
{

来自多个论坛帖子:
WCF REST File upload with additional parameters

[WebGet(UriTemplate="", Method ="POST"]
public string UploadFile(Stream fileContents)

我了解,第一种方法允许直接从普通 HTML 表单发布文件。在我发现的所有论坛帖子中,第二种方法似乎更常见。

你会推荐什么,为什么?应该可以从各种语言和平台访问 REST api。

对于 HttpRequestMessage 方法,如何使用 WCF HttpClient 上传文件?使用 FormUrlEncodedMediaTypeFormatter)

【问题讨论】:

    标签: c# asp.net wcf


    【解决方案1】:

    为了测试 HttpRequestMessage 方法,我使用 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();
        }
    
    }
    

    Index 视图中应该有一个表单,可以回传到 Upload 方法。然后,您可以使用 HttpClient 连接到您的 REST 服务。

    【讨论】:

    • 谢谢 Jed,很遗憾我只能选择一个正确的答案,而且我已经把它给了 JCaffeine。但是投了赞成票。
    • 雷米,不客气,不用担心。很高兴它帮助了你。
    【解决方案2】:

    第一种方法是“更接近金属”并且更灵活,因为您将自己处理 http 请求并构建响应。如果您需要做的只是接受来自客户端的流,则从实现的角度来看,第二个选项要简单得多(在后台,它与第一个方法所做的工作相同)

    我没有你最后一个问题的答案。

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2013-06-17
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2013-04-01
      • 1970-01-01
      相关资源
      最近更新 更多