读取和显示上传文本文件中的MVC [英] Reading and Displaying Uploaded text Files in MVC

查看:139
本文介绍了读取和显示上传文本文件中的MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能读取上传文本文件例如.txt和显示一个文本框的内容?我想做上传的文件的文件转换。我已经成功地上传和验证,我想在按钮的点击阅读的内容,并在准备转换文本框显示它们的文件。我将如何去这样做呢?
上传类

 公共类UploadedFile的
{
    众长尺寸{搞定;组; }
    公共字符串路径{搞定;组; }
    公共字符串名称{;组; }
   //公众诠释长度{搞定;组; }
    公共字符串扩展{搞定;组; }
}公共类HomeController的:控制器
{
    [HTTPGET]
    公众的ActionResult指数()
    {
        ViewBag.Message =修改此模板,以启动你的ASP.NET MVC应用程序。        返回查看();
    }
    [HttpPost]
    公众的ActionResult指数(HttpPostedFileBase文件)
    {
        VAR supportedTypes =新[] {TXT,RTF格式,HTML,XAML,XSLX,PDF,文档,DOCX,CSV};        变种fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);        如果(!supportedTypes.Contains(fileExt))
        {
            ModelState.AddModelError(文件,无效的类型,只有以下几种类型(TXT,RTF,HTML,XSLX,PDF格式,XAML,DOC,DOCX,CSV)的支持。);
            返回查看();
        }
        如果(file.ContentLength> 200000)
        {
            ModelState.AddModelError(文件,文件的大小不能超过200 KB);
            返回查看();
        }
        如果(file.ContentLength大于0)
        {
            变种文件名= Path.GetFileName(file.FileName);
            VAR路径= Path.Combine(使用Server.Mappath(〜/上传),文件名);
            file.SaveAs(路径);
        }        返回RedirectToAction(「指数」);
    }    公众的ActionResult关于()
    {
       VAR UPLOADEDFILES =新的List<&UploadedFile的GT;();
        var中的文件= Directory.GetFiles(使用Server.Mappath(〜/上传));
        的foreach(在文件var文件)
        {
            VAR的fileInfo =新的FileInfo(文件);
            UploadedFile的VAR =新UploadedFile的(){名称= Path.GetFileName(文件)};
            uploadedFile.Size = fileInfo.Length;
            uploadedFile.extension = Path.GetExtension(文件);            uploadedFile.Path =(〜/上传/)+ Path.GetFileName(文件);            uploadedFiles.Add(UploadedFile的);
        }
        返回查看(UPLOADEDFILES);
    }
}

到目前为止上传的table.I被列出的文件想,如果点击按钮,放在桌子下面的文本域里面的内容读取和显示的内容。这样我就可以进行转换。


我将如何实现这一目标?谢谢

 `<脚本方式> $('btnreadfile')点击(函数(){
    document.location ='@ Url.Action(ReadTextFile,家); });&下; /脚本>
      <输入ID =btnreadfileNAME =btnReadFile类型=提交值=读取文件/>    `我的按钮code


解决方案

工作code。经过全面测试

在您 _Layout.cshtml

 < HEAD>
&所述; SCRIPT SRC =HTTP://$c$c.jquery.com/jquery-1.9.1.min.js>&下; /脚本>
< /头>


About.cshtml

标记表达

 <表样式=背景色:浅绿;边界:2px的固体黑色;>
    &所述; TR>
        &所述; TD>
            < B>名称和LT; / B>
        < / TD>
        &所述; TD>
            < B>大小和LT; / B>
        < / TD>
        &所述; TD>
            < B> preVIEW< / B>
        < / TD>
        &所述; TD>
            < B&读取文件< / B>
        < / TD>
    < / TR>
    @foreach(以型号var文件)
    {
        &所述; TR>
            &所述; TD>
                @文件名
            < / TD>
            &所述; TD>
                @(file.Size / 1000)KB
            < / TD>
            &所述; TD>
                @(文件扩展名)
            < / TD>
            &所述; TD>
                <输入ID =btnreadfileNAME =@ file.Name级='btnClick类型=按钮值=读取文件/>
                &所述; textarea的行=4COLS =50>
< / textarea的>
            < / TD>
        < / TR>
    }
< /表>

About.cshtml 所有底部的方式添加这个脚本

 <脚本>
    $阿贾克斯({
        网址:/首页/ ReadTextFile
        键入:GET,
        数据:{文件名:$(本).attr(名称)},
        数据类型:TEXT,
        成功:函数(STR){
            警报(STR);
            $(文本区域)VAL(STR); //这一行必须用更动态的jQuery选择更换,可以选择此按钮旁边的textarea
            //$(this).next(\"textarea\").val(str);
        },
        错误:功能(错误){
            警报(ERR);
        }
    });
});
< / SCRIPT>

在你的控制器


  • 添加引用使用System.Runtime.InteropServices.ComTypes;

  • 添加一个 JsonResult 方法


 公共JsonResult ReadTextFile(字符串文件名)
        {
            字符串retString =的String.Empty;
            字符串路径= Path.Combine(使用Server.Mappath(〜/上传),文件名);
            如果(System.IO.File.Exists(路径))
            {
                如果(Path.GetExtension(路径)==DOC|| Path.GetExtension(路径)==.DOCX)
                {
                    Microsoft.Office.Interop.Word.Application字=新Microsoft.Office.Interop.Word.Application();
                    对象小姐= System.Reflection.Missing.Value;
                    反对readOnly的= TRUE;
                    反对wordPath =路径;
                    Microsoft.Office.Interop.Word.Document文档= word.Documents.Open(
                        REF wordPath,
                        REF小姐,
                        REF只读,已
                        REF思念,思念文献,文献小姐,
                        REF思念,思念文献,文献小姐,
                        REF思念,思念文献,文献小姐,
                        REF思念,思念文献,文献想念,想念参考);
                    的for(int i = 0; I< docs.Paragraphs.Count;我++)
                    {
                        retString + =\\ r \\ n+ docs.Paragraphs [I + 1] .Range.Text.ToString();
                    }
                }
                否则,如果(Path.GetExtension(路径)==TXT)
                {
                    使用(StreamReader的SR =新的StreamReader(路径))
                    {
                        retString = sr.ReadToEnd();
                    }
                }
            }
            返回JSON(retString,JsonRequestBehavior.AllowGet);
        }

请注意:我认为只读具有扩展名的文件 .DOC,.DOCX和.txt 任何其他扩展应进一步处理

Is it possible to read uploaded text files e.g .txt and display the content in a textbox ? I want to do a file conversion of the uploaded files. I've managed to upload and validate the files I would like at the click of a button to read the contents and display them in a textbox ready for conversion. How would I go about doing this? Upload class

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);
    }
}

So far the files uploaded are listed in a table.I would like to read and display the contents if the button is Clicked and the contents placed inside the text area below the table. So I can perform conversion.

How would I achieve this? Thanks

`<script>$('btnreadfile').click(function () {
    document.location = '@Url.Action("ReadTextFile","Home")'; });</script>
      <input id="btnreadfile" name="btnReadFile" type="submit" value="Read File"/>

    `My button Code

解决方案

Working code. Fully tested

in you _Layout.cshtml

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


in your About.cshtml

Table mark up

<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>

in your About.cshtml all the way bottom add this script

<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>

in Your Controller

  • Add reference using System.Runtime.InteropServices.ComTypes;
  • add a JsonResult Method

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);
        }

Note: I have considered to read only files with extension .doc, .docx and .txt any other extensions should be handled further

这篇关于读取和显示上传文本文件中的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆