Preview a varbinary file stored in database on a new tab instead of downloading using ASP.NET MVC

17 Views Asked by At

I have search on the net but couldn't find what I'm looking for. I have a simple app in ASP.NET MVC using C# that lets you upload a file and stored it in a database. That works fine. However, when it comes to view the file attachment, it always download when i click on the link. What i want is to be able to view the file on a new window or tab and not downloading it.

Here's part of my view:

<div class="float-right"> 
    <a href="javascript:;" onclick="PreviewFile(@item.id), '_blank'">
        <i class="fa fa-paperclip" aria-hidden="true"></i>
        View File
    </a> 
</div>

Script file:

<script type="text/javascript"> 
function PreviewFile(fileId)
{ 
    $("#hfFileId").val(fileId);
    $("#btnDownload")[0].click();
}; 
</script>

Controller:

public FileResult PreviewFile(int? fileId)  
{ 
    // if (!string.IsNullOrEmpty(fileId)) 
    if (fileId != null) 
    {
        try 
        { 
            var fileIdx = fileId;
            var myFile = db.AttachmentDocs.SingleOrDefault(x => x.id == fileIdx);
    
            if (myFile != null)
            {
                byte[] fileBytes = myFile.Data;
                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, myFile.Name);
            }
        }
        catch
        {
        }
    }
    
    return null;
}

What I would like is to be able to view the stored file document in a new window or tab and not downloading it. Thanks for your assistance.

0

There are 0 best solutions below