首页 > 解决方案 > 获取 System.Web.HttpPostedFileBase 的内容并写入磁盘

问题描述

真的不知道该怎么做,但我需要从发布的文件中获取内容并将它们写入磁盘。

这是我正在查看的代码。这是一个上传文件的函数:

[HttpPost]
public JsonResult UploadInvoice()
{
    foreach (var file in Request.Files.AllKeys)
    {
        var tempFile = Request.Files[file];
        if (tempFile != null && tempFile.ContentLength > 0)
        {

            var fileName = tempFile.FileName;

            string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "content\\files\\Customer-Returns\\Invoices");
            DirectoryInfo di = Directory.CreateDirectory(filePath);
            filePath = filePath + fileName;

            using (var fs = new FileStream(Request.Files[file], FileMode.Open, FileAccess.Read))
            {
                using (var ms = new MemoryStream())
                {
                    fs.CopyTo(ms);
                    byte[] rawdata = ms.GetBuffer();

                    using (var o = System.IO.File.Create(filePath))
                    {
                        ms.CopyTo(o);
                        fs.Close();
                        ms.Close();
                    }
                }
            }
        }
    }

    return Json(new { result = true });
}

我这里有一个例外:

在此处输入图像描述

不知道到底该怎么做,而且似乎找不到一个明确的例子。任何人都可以帮忙吗?

标签: c#asp.net-mvc

解决方案


好的,所以我完全错误地解决了这个问题,并且没有意识到它会这么容易。

正如@mjwills 上面指出的那样,我必须使用该SaveAs方法。这是代码

[HttpPost]
    public JsonResult UploadInvoice()
    {
        foreach (var file in Request.Files.AllKeys)
        {
            var tempFile = Request.Files[file];
            if (tempFile != null && tempFile.ContentLength > 0)
            {

                var fileName = tempFile.FileName;

                string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "content\\files\\Customer-Returns\\Invoices\\");
                DirectoryInfo di = Directory.CreateDirectory(filePath);
                filePath = filePath + fileName;

                Request.Files[file].SaveAs(filePath);
            }
        }

        return Json(new { result = true });
    }

推荐阅读