c# - 获取 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 });
}
我这里有一个例外:
不知道到底该怎么做,而且似乎找不到一个明确的例子。任何人都可以帮忙吗?
解决方案
好的,所以我完全错误地解决了这个问题,并且没有意识到它会这么容易。
正如@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 });
}
推荐阅读
- laravel - 测试工匠控制台命令时在整数上调用成员函数 expectsOutput()
- r - 如何使用 R 对 PostGIS 数据库查询进行单元测试
- postgresql - Postgres upsert 避免第二个唯一约束?
- python - 致命的 Python 错误:无法从堆栈溢出中恢复。在蟒蛇
- javascript - 在 React 中创建可重新排序的卡片组件
- java - 动态获取 Intellij IDEA (maven) 的内部版本号
- pybind11 - 使用 pybind11 绑定数组
- javascript - 检查用户是否在 Firestore 云功能中是匿名的
- javascript - 收到以下错误:compare.js:1 未捕获的错误:找不到模块“ember”
- r - 识别被矩阵中的一包围的零区域