【问题标题】:Grab contents of System.Web.HttpPostedFileBase and write to disk获取 System.Web.HttpPostedFileBase 的内容并写入磁盘
【发布时间】:2018-06-06 00:09:18
【问题描述】:

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

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

[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


【解决方案1】:

好吧,我完全错了,没想到会这么容易。

正如@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 });
    }

【讨论】:

  • 删除 AllKeys 并进行其他必要的更改以使其编译。代码会更短、更简单、更快。
猜你喜欢
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
相关资源
最近更新 更多