如何根据文件扩展名格式打开文件而不下载文件?

时间:2018-08-15 06:18:02

标签: c# asp.net-core-2.0

在这里,我尝试根据文件的扩展名格式打开ASP.NET MVC CORE 2.0中任何扩展名格式的文件,该文件已保存在数据库中,而无需下载该文件。例如,假设我有ms word文件,因此当我单击该文件时,它应该以word形式打开;如果我有pdf,则应以pdf格式打开而不下载文件。
现在,我的代码中的问题在于,它强制下载文件,而不是根据各自的文件扩展格式打开文件。

任何帮助都将是一个巨大的帮助,谢谢。

以下是我的代码

  public IActionResult ViewFileByFileId (int id)
    {
        DoctorCredentialDocsModel DoctorCredential = new DoctorCredentialDocsModel();
        DoctorCredential = _doctorService.GetDoctorCredentialDetails(id);
        string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
        string strFileFullPath = Path.Combine(AttachPath, DoctorCredential.AttachedFile);

        string contentType = MimeTypes.GetMimeType(strFileFullPath);
        if (!strFileFullPath.Contains("..\\"))
        {
            byte[] filedata = System.IO.File.ReadAllBytes(strFileFullPath);
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = DoctorCredential.FileName,
                Inline = false,
            };
            Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
            return File(filedata, contentType);
        }
        else
        {
            return new NotFoundResult();

        }
    }

1 个答案:

答案 0 :(得分:0)

尝试yo发送类似tihs。 FileContentResult可以为您提供帮助:)

最后看看这个:)

What's the difference between the four File Results in ASP.NET MVC

 public FileContentResult  ViewFileByFileId (int id)
    {
        DoctorCredentialDocsModel DoctorCredential = new DoctorCredentialDocsModel();
        DoctorCredential = _doctorService.GetDoctorCredentialDetails(id);
        string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
        string strFileFullPath = Path.Combine(AttachPath, DoctorCredential.AttachedFile);

        string contentType = MimeTypes.GetMimeType(strFileFullPath);
        if (!strFileFullPath.Contains("..\\"))
        {
            byte[] filedata = System.IO.File.ReadAllBytes(strFileFullPath);
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = DoctorCredential.FileName,
                Inline = false,
            };
            Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
            return File(filedata, contentType);
        }
        else
        {
            return new NotFoundResult();

        }
    }