【发布时间】:2018-01-10 01:03:30
【问题描述】:
我参考了一些 Stack Overflow 的答案,并设法创建了一个允许用户上传文件 (.txt) 的 ASP.NET C# 应用程序。当我运行该应用程序时,会在 Web 浏览器中打开一个页面,其中显示“选择文件”和“确定”。在我选择一个文件并输入“Ok”后,该文件被上传到项目目录中的“uploads”文件夹中。
如何编辑我的代码,而不是将文件上传到“uploads”文件夹,当我点击“确定”后,.txt 文件中的数据也会以 JSON 格式显示在 Web 浏览器页面上?
我知道读取文件的代码应该是这样的:
string data = File.ReadAllText(path);
return data;
但是我不确定如何放入这些代码以使程序按要求运行。
这是我到目前为止所做的:
Index.cshtml
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
【问题讨论】: