在ASP.NET MVC中,可以使用以下代码示例将文件保存到本地网络中的网络附加存储(NAS):
首先,在您的ASP.NET MVC项目中创建一个FileController
控制器。
添加一个SaveFile
动作方法,该方法将接收一个HttpPostedFileBase
参数,表示要保存的文件。
public class FileController : Controller
{
public ActionResult SaveFile(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
// 获取文件的原始文件名
string fileName = Path.GetFileName(file.FileName);
// 获取文件的扩展名
string fileExtension = Path.GetExtension(fileName);
// 生成一个唯一的文件名
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
// 根据NAS的路径和唯一的文件名构建文件的完整路径
string filePath = Path.Combine("\\\\nas\\share\\folder", uniqueFileName);
// 保存文件到NAS
file.SaveAs(filePath);
// 可以在这里执行其他逻辑,如将文件路径保存到数据库等
return RedirectToAction("Index", "Home");
}
return View();
}
}
@using (Html.BeginForm("SaveFile", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
这样,当用户选择文件并点击上传按钮时,文件将被保存到NAS的指定路径中。
请注意,您需要根据您自己的NAS路径和文件保存逻辑进行适当的更改和调整。