2017-02-23 43 views
1

我想將如下的多部分表單數據發佈到WEB API 2控制器。我的數據將有JSON和圖像文件。請幫助我瞭解c#api控制器代碼將如何用於以下數據。在web api中讀取json數據和圖像文件作爲多部分表單數據2

目前我在Request.Content.ReadAsMultipartAsync(provider);收到錯誤:

MIME多流意外結束。 MIME多信息是不完整的

var uploadPath = HttpContext.Current.Server.MapPath("~/Userimage/"); 
Directory.CreateDirectory(uploadPath); 
var provider = new MultipartFormDataStreamProvider(uploadPath); 
await Request.Content.ReadAsMultipartAsync(provider); 

// Files 
// 
foreach (MultipartFileData file in provider.FileData) 
{ 
    Debug.WriteLine(file.Headers.ContentDisposition.FileName); 
    Debug.WriteLine("File path: " + file.LocalFileName); 
} 

// Form data 
// 
foreach (var key in provider.FormData.AllKeys) 
{ 
    foreach (var val in provider.FormData.GetValues(key)) 
    { 
     Debug.WriteLine(string.Format("{0}: {1}", key, val)); 
    } 
} 
return Request.CreateResponse(HttpStatusCode.OK); 
---------------------------acebdf13572468 
Content-Disposition: form-data; name="modelclass" 
Content-Type: application/json 

{ 
    "MessageID": 1, 
    "SenderID": 2, 
    "userType": "sample string 3", 
    "msgCategory": "sample string 4", 
    "msgContent": "sample string 5", 
    "msgDistributedTo": "sample string 6" 
} 
---------------------------acebdf13572468 
Content-Disposition: form-data; name="fieldNameHere"; filename="bg4.jpg" 
Content-Type: image/jpeg 

<@INCLUDE *C:\Users\Lenovo1\Pictures\bg4.jpg*@> 
---------------------------acebdf13572468-- 

回答

0

我一直想這個幾個月前做的,並結束了與下面的代碼:

if (!request.Content.IsMimeMultipartContent("form-data")) 
{ 
    throw new InvalidOperationException("Media type not supported"); 
} 

var root = HttpContext.Current.Server.MapPath("~/App_Data"); 
var provider = new MultipartFormDataStreamProvider(root); 
await request.Content.ReadAsMultipartAsync(provider); 

與您的代碼可能的問題是您嘗試創建應該已經存在的目錄。 試着在代碼的開始處進行內容類型檢查。

相關問題