Asp Mvc Xml上传

时间:2017-02-15 14:37:47

标签: xml asp.net-mvc

我正在上传一个xml并将其发布在我的action方法上。在收到的文件的顶部有信息 ------ WebKitFormBoundarytuARn4Bf71AoeFqG 内容处理:表格数据; NAME = “文件”;文件名= “samplexmp.xml” 内容类型:text / xml 因为我无法在XDocument上加载它。这是我的代码

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

这是我的观点

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

}

如何删除其他数据?

1 个答案:

答案 0 :(得分:1)

您不想读取整个流,因为它是多部分,并且将部分边界写入整个流。

在mvc中读取上传文件的正确方法是

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

来自这篇文章http://rachelappel.com/2015/04/02/upload-and-download-files-using-asp-net-mvc/