我有处理文件上传请求的WebApi控制器。流式传输以进行文件上载的数据位于表单数据集合中。请求中还有另一个表单,其中包含我需要的会话信息。
------WebKitFormBoundarya0caUzBoIAiZmKpk
Content-Disposition: form-data; name="sessionInfo"
{"sessionId":"CC58F82D-DD87-4EA7-8DEF-42CABA045251","client":"","originalUserId":0,"group":0,"cluster":0}
------WebKitFormBoundarya0caUzBoIAiZmKpk
Content-Disposition: form-data; name="file"; filename="import.csv"
Content-Type: application/vnd.ms-excel
"Name","Gender","Company"
"John Smith","male","TestIcon"
"Jane Doe","female","FastTrucks"
------WebKitFormBoundarya0caUzBoIAiZmKpk--
我的问题是如何在c#中分离表单数据集合以获取正确的数据?
现在我有解析导入文件的代码。但我不知道如何访问name="sessionInfo"
表单数据。
答案 0 :(得分:2)
-JS
var files = document.getElementById('uploadFile').files
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
-WebApi
public class ValuesController : ApiController
{
public async Task<IHttpActionResult> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
return BadRequest();
}
var provider = new MultipartMemoryStreamProvider();
string root = System.Web.HttpContext.Current.Server.MapPath("~/Files/");
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
byte[] fileArray = await file.ReadAsByteArrayAsync();
using (System.IO.FileStream fs = new System.IO.FileStream(root + filename, System.IO.FileMode.Create))
{
await fs.WriteAsync(fileArray, 0, fileArray.Length);
}
}
return Ok();
}
}