【问题标题】:Reading and Displaying Uploaded text Files in MVC在 MVC 中读取和显示上传的文本文件
【发布时间】:2013-05-03 03:53:06
【问题描述】:

是否可以读取上传的文本文件,例如 .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

【问题讨论】:

  • 您不确定该怎么做?读取上传的文件?将文件内容传递给视图?
  • 读取上传的文件已经过检查。我尝试了下面的答案,但脚本没有被启动,因为我不知道把它放在哪里。
  • @user2268970 让我知道我的回答是否有帮助,或者您在使用此代码时是否有任何问题。
  • @HaBo 抱歉,您的回答没有多大帮助。我现在已将文本框更改为按钮,但我仍然卡住当前代码是 &lt;script&gt;$('btnreadfile').click(function () { document.location = '@Url.Action("ReadTextFile","Home")'; });&lt;/script&gt; &lt;input id="btnreadfile" name="btnReadFile" type="submit" value="Read File"/&gt; &lt;/td&gt; 不知道从这里去哪里
  • @user2268970 让我看看能不能帮你解决这个问题。你能分享你的标记并向我解释你想要什么吗?你可以在这里粘贴标记jsfiddle.net/habo/tNUTg

标签: asp.net-mvc file-conversion


【解决方案1】:

工作代码。全面测试

在你_Layout.cshtml

<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>

在您的 About.cshtml

表格标记

<table style="background-color: lightgreen; border: solid 2px black;">
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            <b>Size</b>
        </td>
        <td>
            <b>Preview</b>
        </td>
        <td>
            <b>Read File</b>
        </td>
    </tr>
    @foreach (var file in Model)
    {    
        <tr>
            <td>
                @file.Name
            </td>
            <td>
                @(file.Size / 1000) KB
            </td>
            <td>
                @(file.extension)
            </td>
            <td>
                <input id="btnreadfile" name="@file.Name" class='btnClick' type="button" value="Read File"/>
                <textarea rows="4" cols="50">
</textarea>
            </td>
        </tr>   
    }
</table>

在你的About.cshtml一路底部添加这个脚本

<script>
    $.ajax({
        url: "/Home/ReadTextFile", 
        type: "GET",
        data: { fileName: $(this).attr("name") },
        DataType: "text",
        success: function (str) {
            alert(str);
            $("textarea").val(str); // this line has to be replaced with more dynamic jQuery selector that can select this button next textarea
            //$(this).next("textarea").val(str);
        },
        error: function (err) {
            alert(err);
        }
    });
});
</script>

在你的控制器中

  • 添加参考using System.Runtime.InteropServices.ComTypes;
  • 添加一个JsonResult方法

public JsonResult ReadTextFile(string fileName)
        {
            string retString = string.Empty;
            string path = Path.Combine(Server.MapPath("~/uploads") , fileName );
            if (System.IO.File.Exists(path))
            {
                if (Path.GetExtension(path) == "doc" || Path.GetExtension(path) == ".docx")
                {
                    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    object miss = System.Reflection.Missing.Value;
                    object readOnly = true;
                    object wordPath = path;
                    Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(
                        ref wordPath, 
                        ref miss, 
                        ref readOnly, 
                        ref miss, ref miss, ref miss, 
                        ref miss, ref miss, ref miss, 
                        ref miss, ref miss, ref miss, 
                        ref miss, ref miss, ref miss, ref miss);
                    for (int i = 0; i < docs.Paragraphs.Count; i++)
                    {
                        retString += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
                    }
                }
                else if (Path.GetExtension(path) == "txt")
                {
                    using (StreamReader sr = new StreamReader(path))
                    {
                        retString = sr.ReadToEnd();
                    }
                }
            }
            return Json(retString, JsonRequestBehavior.AllowGet);
        }

注意:我考虑过只读取扩展名为 .doc, .docx and .txt 的文件,任何其他扩展名都应进一步处理

【讨论】:

  • 第一段代码去哪里了?我需要创建一个新课程吗?
  • @HaBo:这两个代码示例的几乎每一行都是无效的。 javascript: Checked、Value、“ulr”、DataType、“cjeckbox”要么大小写错误,要么拼写错误。 C:\temp 的硬编码目录以及所有文件都具有 .txt 扩展名的假设。 ReadAllLines,然后在字符串数组上调用 ToString()(它不会返回文件内容,它会返回一个字面意思为 [System.String[]]“的字符串。您是否测试过有关您发布的代码的任何内容?
  • @rossisdead 这是一个伪代码,id id 没有测试它。我应该在答案中解释它。但是你在字符串数组 tostirng() 上是对的,我改变了它。
  • @user2268970 在您的视图中使用
  • @HaBo 干得好。你能解释一下excel文件吗?我试图读取 excel 文件的内容不起作用。你能帮个忙吗?
猜你喜欢
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-02
  • 2015-03-19
  • 2011-07-08
  • 2014-09-22
  • 1970-01-01
  • 2013-09-07
相关资源
最近更新 更多