2

I have a ASP.NET MVC project that needs an API controller which will accept a posted multipart form and extract the data out of the <formroot> xml tag (which is highlighted)

I am struggling on getting this working any help would be greatly appreciated

enter image description here

Currently I have a controller called UploadController and this is the code I currently have

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);
        }
    }
}

I am unsure the best way to get the data from within the formroot, also forgive me if any of the code above is not correct.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Paul Coan
  • 302
  • 1
  • 3
  • 15

2 Answers2

0

I always use solution below:

<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: "upload()" javascript function uses jquery to post the form.

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

In my controller i use as a modelbinder "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);
}
Fabio Silva Lima
  • 704
  • 6
  • 14
0

Inside the web API controller you can access the XML file by using the code below :-

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

If you have more than one files posted, replace Files[0] with respective count 1 or 2 etc. Now you can load the file into a XmlDocument Object and extract the required node from it like :-

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);

Then you can perform whatever you functionality is provided with the node.

Jose Francis
  • 950
  • 13
  • 28