是否可以读取上传的文本文件,例如 .txt 并在文本框中显示内容?我想对上传的文件进行文件转换。我已经成功上传并验证了我想要的文件,只需单击一个按钮即可读取内容并将它们显示在准备转换的文本框中。我该怎么做呢?上传课程
public class UploadedFile
{
public long Size { get; set; }
public string Path { get; set; }
public string Name { get; set; }
// public int Length { get; set; }
public string extension { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
var supportedTypes = new[] { "txt", "rtf", "html", "xaml", "xslx" ,"pdf", "doc", "docx", "csv" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
if (!supportedTypes.Contains(fileExt))
{
ModelState.AddModelError("file", "Invalid type. Only the following types (txt, rtf, html, xslx, pdf, xaml, doc, docx, csv) are supported.");
return View();
}
if (file.ContentLength > 200000)
{
ModelState.AddModelError("file", "The size of the file should not exceed 200 KB");
return View();
}
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
public ActionResult About()
{
var uploadedFiles = new List<UploadedFile>();
var files = Directory.GetFiles(Server.MapPath("~/uploads"));
foreach(var file in files)
{
var fileInfo = new FileInfo(file);
var uploadedFile = new UploadedFile() {Name = Path.GetFileName(file)};
uploadedFile.Size = fileInfo.Length;
uploadedFile.extension = Path.GetExtension(file);
uploadedFile.Path = ("~/uploads/") + Path.GetFileName(file);
uploadedFiles.Add(uploadedFile);
}
return View(uploadedFiles);
}
}
到目前为止,上传的文件都列在一个表格中。如果单击按钮并将内容放在表格下方的文本区域内,我想阅读并显示内容。所以我可以执行转换。
我将如何实现这一目标?谢谢
`<script>$('btnreadfile').click(function () {
document.location = '@Url.Action("ReadTextFile","Home")'; });</script>
<input id="btnreadfile" name="btnReadFile" type="submit" value="Read File"/>
`My button Code