当我从数据库中获取文件名时,如何在iframe中显示文档文件? [英] How can show document file in iframe when i get the file name from database?

查看:284
本文介绍了当我从数据库中获取文件名时,如何在iframe中显示文档文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从数据库中获取文件名时,如何在iframe中显示文档文件?我的数据库表名为File,而视图模型为MyFileModel.

How can show document file in iframe when i get the file name from database?My database table name is File and my viewmodel is MyFileModel.

    public ActionResult Create(HttpPostedFileBase file)
       {         
        try
        {
            if (ModelState.IsValid)
            {
                db.Files.Add(new File()
                {
                    FileName = Path.GetFileName(file.FileName)
                });
                db.SaveChanges();
            }
        }
        catch (Exception)
        {
            var error = "Sorry not save";
        }
        return Content("");
    }

     public FileStreamResult GetPDF()
        {
            var file = db.Files.Single(s => s.Id == 1);
            FileStream fs = new FileStream(Server.MapPath(file.FileName), FileMode.Open, FileAccess.Read);
            return File(fs, "application/pdf");
            //return View(Server.MapPath("~/File/SegmentAdd.txt"));
            //return File(fs,"text/plain");
        }

   <div id="frame">
    <iframe src="@Url.Action("GetPDF","Home")" width="900px" height="500px"></iframe>
  </div>
`

推荐答案

我发布的答案都是假设的,我对您的解决方案没有清楚的了解. 如果您不保存物理文件,请尝试将其保存在文件夹中,然后将名称保存在数据库中,或者尝试将整个路径保存在数据库中.

The answer which I am posting is all on an assumption, I do not have clear picture of your solution. If you are not saving a physical file try to save it in a folder and then save the name in the DB OR try to save the entire path in the DB.

方法1 :

如果要将文件保存在文件夹中,请说 文件 最好的方法是在web.config(位于根目录的.config文件中)中添加密钥如下

If you are saving the file in a folder say File best way is to add a key in the web.config(.config file which is at the root) as follows

<add key="FilePath" value= "~/File/"/>

然后按如下所示修改您的C#代码

and then modify your C# code as follows

public FileStreamResult GetPDF()
        {
            var file = db.Files.Single(s => s.Id == 1);
            string fileName = file.FileName;
            string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
            FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
            return File(fs,"text/plain"); // "text/plain" if your file content-type is text file
            //return View(Server.MapPath("~/File/SegmentAdd.txt"));
            //return File(fs,"text/plain");
        }

方法2 :

如果要保存整个路径,那么它将使编码变得更加简单,并且无需更改已编写的代码,只需进行相同操作即可.

If you are saving the entire path then it makes coding much more simpler and you need not change the code you have written, just go ahead with the same.

希望这会对您有所帮助.

Hope this would help you.

这篇关于当我从数据库中获取文件名时,如何在iframe中显示文档文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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