【问题标题】:How do I upload a file stream to the web API 2 in ASP.NET via JSON object?如何通过 JSON 对象将文件流上传到 ASP.NET 中的 Web API 2?
【发布时间】:2016-07-04 09:07:17
【问题描述】:

我有一个场景,我想通过 JSON 对象将文件流从客户端(我正在使用 AngularJS)上传到 asp .net 中的 Web Api。 所以 JSON 对象中会有一些字段,其中一个字段是文件流。我如何创建一个 JSON 对象并将其发送到 web api,从而在 api 端将模型绑定到我的模型。

    $scope.fileUploadData = {
        TextId: 304765,
        DocumentId: 0,
        PatientId: 166158,
        file://This is my file stream property in JSON
}

    public ApiActionResult CreateDocument(DocumentVM model)
{
  //Some logic here.....
}

// DocumentVM class will be as follows
public class DocumentVM
{
        long TextId;
        long DocumentId;
        long PatientId;
        Stream file;
}

请提供示例代码 sn-ps 如何实现它。
我试过的: 我用谷歌搜索了很多,但我发现了使用多部分表单数据之类的解决方案。在其中附加 JSON 和文件流,然后将其发送到 web api。我使用以下逻辑来提取多部分表单数据。

    public async Task<ApiActionResult> CreateDocument()
{
  MultipartFormDataStreamProvider provider = 
            new MultipartFormDataStreamProvider(Path.GetTempPath());
            var result = await Request.Content.ReadAsMultipartAsync(provider);
            var model= result.FormData["Metadata"];
            var fileData = result.FileData;//How it will retriev the file data
}

【问题讨论】:

  • 使用简单的 json 对象,您不能流式传输文件。您需要创建多部分请求。在 javascript 端,您需要创建 File 对象,该对象将使用多部分请求传递给服务器。
  • 那么除了多部分表单数据之外没有其他选项可以将流发送到API?

标签: angularjs json asp.net-web-api2


【解决方案1】:

不知道你的问题是否有解决方案......但我有同样的情况,我像下面这样解决了它

有两种方法可以做到这一点

方法一: 使用 MultipartFormData 将您的流直接传递给您的 WebApi,检查此link

在您的问题中,您提到您尝试过这种方法但没有得到任何一天..我猜您没有在 html 表单中使用enctype="multipart/form-data"

方法 2:您可以创建一个自定义模型绑定器,然后可以在您的操作模型上进行装饰,如下所示

public class MyModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            // Extract the posted data from the request
            // Convert the base64string to Stream
            // Extract the model from the bindingcontext
            // Assign the model's property with their values accordingly   
        }
    }

在你的控制器中

public ApiActionResult SaveDocument([ModelBinder(typeof(MyModelBinder))]DocumentVM contentDTO)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-03
    • 2014-05-15
    • 2013-02-26
    • 1970-01-01
    • 2023-03-22
    • 2021-07-07
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多