Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 在MVC中读取和显示上传的文本文件_Asp.net Mvc_File Conversion - Fatal编程技术网

Asp.net mvc 在MVC中读取和显示上传的文本文件

Asp.net mvc 在MVC中读取和显示上传的文本文件,asp.net-mvc,file-conversion,Asp.net Mvc,File Conversion,是否可以读取上传的文本文件(如.txt)并在文本框中显示内容?我想对上传的文件进行文件转换。我已经成功上传并验证了我想要的文件,只需点击一个按钮即可读取内容并将其显示在文本框中,以备转换。我该怎么做呢? 上传类 public class UploadedFile { public long Size { get; set; } public string Path { get; set; } public string Name { get; set; } // p

是否可以读取上传的文本文件(如.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);
    }
}
公共类上载文件
{
公共长大小{get;set;}
公共字符串路径{get;set;}
公共字符串名称{get;set;}
//公共整数长度{get;set;}
公共字符串扩展名{get;set;}
}
公共类HomeController:控制器
{
[HttpGet]
公共行动结果索引()
{
ViewBag.Message=“修改此模板以跳转启动ASP.NET MVC应用程序。”;
返回视图();
}
[HttpPost]
公共操作结果索引(HttpPostedFileBase文件)
{
var-supportedTypes=new[]{“txt”、“rtf”、“html”、“xaml”、“xslx”、“pdf”、“doc”、“docx”、“csv”};
var fileExt=System.IO.Path.GetExtension(file.FileName).Substring(1);
如果(!supportedTypes.Contains(fileExt))
{
AddModelError(“文件”,“无效类型。仅支持以下类型(txt、rtf、html、xslx、pdf、xaml、doc、docx、csv”);
返回视图();
}
如果(file.ContentLength>200000)
{
AddModelError(“文件”,“文件大小不应超过200 KB”);
返回视图();
}
如果(file.ContentLength>0)
{
var fileName=Path.GetFileName(file.fileName);
var path=path.Combine(Server.MapPath(“~/uploads”),文件名);
file.SaveAs(路径);
}
返回操作(“索引”);
}
关于()的公共行动结果
{
var uploadedFiles=新列表();
var files=Directory.GetFiles(Server.MapPath(“~/uploads”);
foreach(文件中的var文件)
{
var fileInfo=新文件信息(文件);
var uploadedFile=new uploadedFile(){Name=Path.GetFileName(file)};
uploadedFile.Size=fileInfo.Length;
uploadedFile.extension=Path.GetExtension(文件);
uploadedFile.Path=(“~/uploads/”)+Path.GetFileName(文件);
uploadedFiles.Add(uploadedFile);
}
返回视图(上传文件);
}
}
到目前为止,上传的文件都列在一个表中。如果单击按钮并将内容放在表下的文本区域内,我想阅读并显示内容。所以我可以进行转换

我将如何实现这一点?谢谢

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

    `My button Code
`$('btnreadfile')。单击(函数(){
document.location='@Url.Action(“ReadTextFile”,“Home”);});
`我的按钮代码

工作代码。充分测试

在你\u Layout.cshtml

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

注意:我已经考虑过使用扩展名为
.doc、.docx和.txt的只读文件
任何其他扩展名都应该进一步处理

代码的第一段到哪里去了?我需要创建一个新类吗?@HaBo:这两个代码示例的几乎每一行都是无效的。javascript:Checked、Value、“ulr”、DataType、“cjeckbox”的大小写不正确或拼写不正确。C:\temp的硬编码目录,并假设所有文件都有.txt扩展名。ReadAllLines,然后在字符串数组上调用ToString()(该数组不会返回文件内容,它将返回一个字面上为[System.string[]的字符串)“。你测试过你发布的代码吗?@rossisdead这是一个伪代码,我没有测试它。我应该在答案中解释它。但是你对字符串数组tostirn()的测试是正确的。”我更改了它。@user2268970在您的视图中使用tags@HaBo很好的工作。你能解释一下excel文件吗?我试图读取的excel文件不起作用。你能帮个忙吗?你到底不知道怎么做?读取上传的文件?将文件内容传递给视图?读取具有een选中。我尝试了下面的答案,但脚本没有启动,因为我不知道确切的位置。@user2268970请告诉我我的答案是否有用,或者您在使用此代码时是否遇到任何问题。@HaBo抱歉,您的答案没有太大帮助。我现在已将文本框更改为一个按钮,但我仍然无法确定当前代码是
$('btnreadfile')。单击(函数(){document.location='@Url.Action(“ReadTextFile”,“Home”);};
不确定从何处开始here@user2268970让我看看我是否能帮你。你能分享你的标记并解释一下你想要什么。你可以在这里粘贴标记
<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>
<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>
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);
        }