[英]How do I upload a file stream to the web API 2 in ASP.NET via JSON object?
我有一種情況,我想通過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;
}
請提供示例代碼片段如何實現。
我嘗試過的事情:我在Google上搜索了很多,但是找到了使用多部分表單數據的解決方案。 在其中附加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
}
不知道您是否為您的問題找到了解決方案...但是我遇到了相同的情況,並且如下所示解決了問題
有兩種相同的方法
方法1:使用MultipartFormData將流直接傳遞到WebApi,請選中此鏈接
在您的問題中,您提到您嘗試了這種方法,但是沒有一天。.我的猜測是您沒有在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.