2

我有需要的API控制器将接受一个发布多形式和提取数据出来<formroot> XML标签(这是高亮)多形式 - 网络API

我挣扎了ASP.NET MVC项目在得到这个工作的任何帮助,将不胜感激

enter image description here

目前,我已呼吁UploadController控制器,这是代码我现在有

public class UploadController : ApiController 
{ 
    public async Task<HttpResponseMessage> PostFormData() 
    { 
     if (!Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.BadRequest); 
     } 

     string root = HttpContext.Current.Server.MapPath("~/App_Data"); 
     var provider = new MultipartFormDataStreamProvider(root); 

     try 
     { 
      //Need to get the data from within the formroot tag 


      return Request.CreateResponse(HttpStatusCode.OK); 
     } 
     catch (Exception e) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 
} 

我不确定从formroot获取数据的最佳方式,如果上述任何代码不正确,也请原谅我。

+1

你究竟在哪里卡住?写POST?控制器?分析消息?你有什么代码? –

+0

道歉我的问题是模糊的,我现在编辑和充实 –

+0

它看起来像你想获取上传的文件数据?它是否正确? – Hypnobrew

回答

0

里面的网络API控制器,你可以通过下面的代码访问XML文件: -

HttpPostedFile xmlFile = HttpContext.Current.Request.Files[0]; 

如果您已发布多个文件,以及相应的计数1 [0]替换的文件或2等 现在可以将文件加载到如下的对象和从中提取所要求的节点,如: -

XmlDocument doc = new XmlDocument(); 
doc.Load(xmlFile.InputStream); 
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("ab", "www.w3.org/2001/XMLSchema-instance"); 
XmlNode node = doc.SelectSingleNode("//ab:formroot", nsmgr); 

然后,可以执行任何你功能随节点一起提供。

+0

你先生真棒!让我到我需要的地方谢谢 –

+0

@Paul Coan干杯人! –

0

我总是用以下解决方案:

<form action="/Home/Upload" enctype="multipart/form-data" id="upload" method="post"> 
     @Html.AntiForgeryToken() 
     <input type="file" class="file" id="file" name="file" onchange="javascript:upload(this);" /> 
</form> 

PS: “上传()” JavaScript函数使用jQuery的发布形式。

function upload(obj) { 
    var p = $(obj).parent(); 
    if (p.get(0).tagName != 'FORM') { 
     p = p.parent(); 
    } 
    p.submit(); 
} 

在我的控制器中,我用作模型绑定器“HttpPostedFileBase”。

[HttpPost] 
[ValidateAntiForgeryToken] 
public RedirectResult Upload(HttpPostedFileBase file) 
{ 
    try 
    { 
     //physical path there you will save the file. 
     var path = @"c:\temp\filename.txt"; 
     file.SaveAs(path); 
    } 
    catch (UploadException ex) 
    { 

    } 

    var url = "put here same url or another url"; 

    return RedirectResult(url); 
}