0

I am uploading an xml and the posting it on my action method.At the top of the received file there is information ------WebKitFormBoundarytuARn4Bf71AoeFqG Content-Disposition: form-data; name="file"; filename="samplexmp.xml" Content-Type: text/xml because of which I cannot load it on XDocument.This is my code

public ActionResult PostXml()
    {
        string xml = "";
        if (Request.InputStream != null)
        {
            StreamReader stream = new StreamReader(Request.InputStream);
            string x = stream.ReadToEnd();
            xml = HttpUtility.UrlDecode(x);
            var xmldocument = XDocument.Parse(xml);//Exception (Invalid data at the root)
        }
        return View();
    }

This is my view

@using (Html.BeginForm("PostXml", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   input type="file" name="file" 
        input type="submit" value="Upload" 

}

How can I remove that additional data?

2
  • 1
    I don't think you want to be reading the whole input stream. and your action method looks incorrect. Check out rachelappel.com/2015/04/02/… Commented Feb 15, 2017 at 14:59
  • Thanks Fran .It worked. Commented Feb 15, 2017 at 15:08

1 Answer 1

1

You don't want to read the whole stream because it is multipart and is going to have part boundaries written into the whole stream.

the correct way of reading the uploaded file in mvc is

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    try
    {
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
            file.SaveAs(path);
        }
        ViewBag.Message = "Upload successful";
        return RedirectToAction("Index");
    }
    catch
    {
        ViewBag.Message = "Upload failed";
        return RedirectToAction("Uploads");
    }
}

from this article http://rachelappel.com/2015/04/02/upload-and-download-files-using-asp-net-mvc/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.