2016-11-16 78 views
7

我一个多形式的数据发送到我的Web API是这样的:ASP.NET如何在Web API中读取多部分表单数据?

string example = "my string"; 
HttpContent stringContent = new StringContent(example); 
HttpContent fileStreamContent = new StreamContent(stream); 
using (var client = new HttpClient()) 
{ 
    using (var content = new MultipartFormDataContent()) 
    { 
     content.Add(stringContent, "example", "example"); 
     content.Add(fileStreamContent, "stream", "stream"); 
     var uri = "http://localhost:58690/api/method"; 
     HttpResponseMessage response = await client.PostAsync(uri, content); 

,这是Web API:

[HttpPost] 
[Route("api/method")] 
public async Task<HttpResponseMessage> Method() 
    { 
     // take contents and do something 
    } 

如何读取字符串和请求主体在我的Web API的流?

回答

4

这应该帮助您开始:

var uploadPath = HostingEnvironment.MapPath("/") + @"/Uploads"; 
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)); 
    } 
} 
+0

谢谢!如果我不需要在服务器上保存Web API的参数,但只能操作它们,那么过程是一样的吗? – Giobbo

+0

@Giobbo ...我不确定保存参数是什么意思。你的意思是请求主体的内容(文件等)?如果是这样,不,你可以将它们保存在内存中,但要注意大文件。 –

+0

是的,抱歉(我的英文很糟糕)。我的意思是我的例子中的主体内容,流和字符串。我只想从身体中拿出一些东西与他们做一些事情。 – Giobbo

0

要发送多个文件

 System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; 

     //// CHECK THE FILE COUNT. 
     for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) 
     { 
      System.Web.HttpPostedFile hpf = hfc[iCnt]; 
      string Image = UploadDocuments.GetDocumentorfileUri(hpf); 
      UploadDocuments.UploadDocumentsIntoData(Image, hpf.FileName, id); 

     } 

Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME

9

这是代码,我以前用过的接收JSON数据+的可选文件:

var result = await Request.Content.ReadAsMultipartAsync(); 

var requestJson = await result.Contents[0].ReadAsStringAsync(); 
var request = JsonConvert.DeserializeObject<MyRequestType>(requestJson); 

if (result.Contents.Count > 1) 
{ 
    var fileByteArray = await result.Contents[1].ReadAsByteArrayAsync(); 
    ... 
} 

它真的很整洁,你可以在这样的请求中组合不同类型的数据。

编辑:如何发送该请求的例子:

let serialisedJson = JSON.stringify(anyObject); 
let formData = new FormData(); 
formData.append('initializationData', serialisedJson); 
// fileObject is an instance of File 
if (fileObject) { 
    // the 'jsonFile' name might cause some confusion: 
    // in this case, the uploaded file is actually a textfile containing json data 
    formData.append('jsonFile', fileObject); 
} 

return new Promise((resolve, reject) => { 
    let xhr = new XMLHttpRequest(); 
    xhr.open('POST', 'http://somewhere.com', true); 
    xhr.onload = function(e: any) { 
     if (e.target.status === 200) { 
      resolve(JSON.parse(e.target.response)); 
     } 
     else { 
      reject(JSON.parse(e.target.response)); 
     } 
    }; 
    xhr.send(formData); 
}); 
+0

请求是什么样的? – hashtable

+1

对于这个例子,在我的客户端代码中,我实例化了一个FormData类,然后添加序列化的json(所以不是对象本身,但字符串版本),并且可以选择添加一个File对象,然后发送FormData实例与XmlHttpRequest(即时通讯实际上使用angular2来做这个请求,但角度的Http服务不允许你这样做,所以你需要自己处理XmlHttpRequest) – Davy

+0

我其实只是发送一个FormData对象的一些字段并通过$ http服务为我的项目昨晚工作的文件。最主要的是我必须明确地将content-type设置为undefined ..并且我没有序列化任何东西,只需将body设置为FormData对象。 即时使用Angular 1.6。 – hashtable

0
You can read content and get all file informations (in my example image) 
without copying to local disk on this way: 

public async Task<IHttpActionResult> UploadFile() 
{ 
    if (!Request.Content.IsMimeMultipartContent()) 
    { 
     return StatusCode(HttpStatusCode.UnsupportedMediaType); 
    }   

    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync(); 

    foreach (var stream in filesReadToProvider.Contents) 
    { 
     //getting of content as byte[], picture name and picture type 
     var fileBytes = await stream.ReadAsByteArrayAsync(); 
     var pictureName = stream.Headers.ContentDisposition.FileName; 
     var contentType = stream.Headers.ContentType.MediaType; 
    } 
} 
相关问题