This is a migrated thread and some comments may be shown as answers.

OnClientFileOpen in RADFILEEXPLORER(How to open file in with their original extension.)

1 Answer 596 Views
FileExplorer
This is a migrated thread and some comments may be shown as answers.
Ajay
Top achievements
Rank 2
Ajay asked on 06 Oct 2009, 07:55 AM
Hi Telerik !

Iam using the RAD FILE EXPLROER in one of my project. I have uploade the files with the following extensions :-

.docx,
.doc, .xslx
.pdf & many images file such as .jpeg,.jpg,.gif,.bmp.

I have implemented the following javascript function in order to open the file in the context menu:-

 function OnClientFileOpen(oExplorer, args) {  
            debugger;  
            var item = args.get_item();  
            var fileExtension = item.get_extension();  
 
            //var fileDownloadMode = document.getElementById("chkbxDownoaldFile").checked;  
            if ((fileExtension == "jpg" || fileExtension == "gif") && fileExtension == "xlsx" || fileExtension == "docx") {// Download the file   
                // File is a image document, do not open a new window  
                args.set_cancel(true);  
 
                // Tell browser to open file directly  
                var requestImage = "FileSystemHandler.ashx?path=" + item.get_url();  
                document.location = requestImage;  
            //}  
        }  
 
 
 
 I have the following code implemented on to my FileSystemHandler.ashx file :-
<%@ WebHandler Language="C#" Class="Handler" %> 
using System;  
using System.Data;  
using System.Configuration;  
using System.Web;  
using System.IO;  
using System.Collections.Generic;  
using System.Xml;  
 
public class Handler : IHttpHandler  
{  
    #region IHttpHandler Members  
 
    string pathToConfigFile = "~/App_Data/MappingFile.mapping";  
    private HttpContext _context;  
    private HttpContext Context  
    {  
        get  
        {  
            return _context;  
        }  
        set  
        {  
            _context = value;  
        }  
    }  
 
 
    public void ProcessRequest(HttpContext context)  
    {  
        Context = context;  
 
        if (context.Request.QueryString["path"] == null)  
        {  
            return;  
        }  
 
        string virtualPathToFile = Context.Server.HtmlDecode(context.Request.QueryString["path"]);  
        string physicalPathToFile = "";  
        Dictionary<string, string> mappedPathsInConfigFile = this.GetMappingsFromConfigFile();  
        foreach (KeyValuePair<string, string> mappedPath in mappedPathsInConfigFile)  
        {  
            if (virtualPathToFile.ToLower().StartsWith(mappedPath.Key.ToLower()))  
            {  
                // Build the physical path to the file ;  
                physicalPathToFile = virtualPathToFile.Replace(mappedPath.Key, mappedPath.Value).Replace("/", "\\");  
 
                break;// Brak the foreach loop ;  
            }  
        }  
 
        if (physicalPathToFile == null)  
        {  
            return;  
        }  
 
        System.IO.StreamReader streamReader = new System.IO.StreamReader(physicalPathToFile);  
        System.IO.BinaryReader br = new System.IO.BinaryReader(streamReader.BaseStream);  
 
        byte[] bytes = new byte[streamReader.BaseStream.Length];  
 
        br.Read(bytes, 0, (int)streamReader.BaseStream.Length);  
 
        if (bytes == null)  
        {  
            return;  
        }  
 
        streamReader.Close();  
        br.Close();  
        string extension = System.IO.Path.GetExtension(physicalPathToFile);  
        string fileName = System.IO.Path.GetFileName(physicalPathToFile);  
 
        if (extension == ".jpg")  
        { // Handle *.jpg and  
            WriteFile(bytes, fileName, "image/jpeg jpeg jpg jpe", context.Response);  
        }  
        else if (extension == ".gif")  
        {// Handle *.gif  
            WriteFile(bytes, fileName, "image/gif gif", context.Response);  
        }  
    }  
    private void WriteFile(byte[] content, string fileName, string contentType, HttpResponse response)  
    {  
        response.Buffer = true;  
        response.Clear();  
        response.ContentType = contentType;  
 
        response.AddHeader("content-disposition", "attachment; filename=" + fileName);  
 
        response.BinaryWrite(content);  
        response.Flush();  
        response.End();  
    }  
      
      
    public bool IsReusable  
    {  
        get  
        {  
            return false;  
        }  
    }  
 
 
    /// <summary> 
    /// Retrieves the mapping for view paths ;  
    /// </summary> 
    /// <param name="virtualPathToConfigFile">The fvirtual path to the config file </param> 
    /// <returns>The mappings </returns> 
    private Dictionary<string, string> GetMappingsFromConfigFile()  
    {  
        XmlDocument configFile = new XmlDocument();  
        string physicalPathToConfigFile = Context.Server.MapPath(this.pathToConfigFile);  
        configFile.Load(physicalPathToConfigFile);// Load the configuration file ;  
 
        XmlElement rootElement = configFile.DocumentElement;  
        XmlNode mappingsSection = rootElement.GetElementsByTagName("Mappings")[0]; // get all mappings ;  
 
        Dictionary<string, string> mappingsFromConfigFile = new Dictionary<string, string>();  
        foreach (XmlNode mapping in mappingsSection.ChildNodes)  
        {  
            XmlNode virtualPathAsNode = mapping.SelectSingleNode("child::VirtualPath");  
            XmlNode physicalPathAsNode = mapping.SelectSingleNode("child::PhysicalPath");  
            mappingsFromConfigFile.Add(this.AddSlashAtEndOfVirtualPath(virtualPathAsNode.InnerText), this.AddSlashAtEndOfPhysicalPath(physicalPathAsNode.InnerText));  
        }  
 
        return mappingsFromConfigFile;  
    }  
 
    /// <summary> 
    /// Gets the path to the generic handler. It should be a virtual path  
    /// </summary> 
    /// <returns>Path to the generic handler</returns> 
    private string GetPathTogenericHandler()  
    {  
        XmlDocument configFile = new XmlDocument();  
        string physicalPathToConfigFile = Context.Server.MapPath(this.pathToConfigFile);  
        configFile.Load(physicalPathToConfigFile);// Load the configuration file ;  
 
        XmlElement rootElement = configFile.DocumentElement;  
        XmlNode handlerPathSection = rootElement.GetElementsByTagName("genericHandlerPath")[0]; // get all mappings ;  
 
        return handlerPathSection.InnerText;  
    }  
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////  
    //  The custom methods   
    //////////////////////////////////////////////////////////////////////////////////////////////////////////  
    /// <summary> 
    /// Adds a backslash at the end of a physical path if the slash does not exists ;  
    /// </summary> 
    /// <param name="physicalPath">Physical path</param> 
    /// <returns></returns>  
    private string AddSlashAtEndOfPhysicalPath(string physicalPath)  
    {  
 
        if (!physicalPath.EndsWith("\\"))  
        {  
            return physicalPath + "\\";  
        }  
        else  
        {  
            return physicalPath;  
        }  
    }  
 
    /// <summary> 
    /// Adds a backslash at the end of a virtual path if the slash does not exists ;  
    /// </summary> 
    /// <param name="virtualPath">Virtual path</param> 
    /// <returns></returns>  
    private string AddSlashAtEndOfVirtualPath(string virtualPath)  
    {  
 
        if (!virtualPath.EndsWith("/"))  
        {  
            return virtualPath + "/";  
        }  
        else  
        {  
            return virtualPath;  
        }  
    }  
    #endregion  
    } 
Also, I have used the following in the ASPX Page :-

<telerik:RadFileExplorer runat="server" ID="DocumentsRadFileExplorer" Width="734px" 
                    Height="400px" VisibleControls="All" EnableCreateNewFolder="true" EnableCopy="true" EnableOpenFile="true" 
                    OnClientMove="OnClientMove" OnClientFileOpen="OnClientFileOpen" OnClientDelete="OnClientDelete" OnClientLoad="attachHandlers" > 
             <Configuration SearchPatterns="*.*"></Configuration> 
                </telerik:RadFileExplorer> 
Now whenever I try to open the file with .doc or .docx or .pdf extension file does not get open in MS word format. PDF file opens ups but with its name changed as FileHandler.pdf.

Apart form that, I have used all the sample that has been sent by all your member earlier but all in vain.

Below is the list of javascript function that I have used so far :-
       function OnClientFileOpen(sender, args)      
{  
   var item = args.get_item();  
   if (item && !item.isDirectory() && (item.get_extension() == "docx") && (item.get_extension() == "doc"))  
   {  
       //file is a MS Office document, do not open a new window.    
       args.set_cancel(true);  
         
       //tell browser to open file directly  
       //window.location.href = item.get_url();  
       var requestImage = "Handler.ashx?path=" + item.get_url();  
       window.location.href = requestImage;  
         
   }  
}   
      
        function OnExplorerFileOpen(oExplorer, args) {  
            var item = args.get_item();  
            var fileExt = item.get_extension();  
            if (fileExt == "jpg") {  
                var oWindowManager = oExplorer.get_windowManager();  
                args.set_cancel(true);  
                var newURL = "Popup.aspx?path=" + item.get_path();  
                var oWindow = oWindowManager.open(newURL, "RadWindow1");  
                oWindow.setSize(500, 500);  
            }  
            else if (fileExt == "pdf") {  
                setTimeout(  
                        function() {  
                            var oWindow = oExplorer.get_windowManager().getActiveWindow();  
                            oWindow.setSize(500, 600);  
                        }, 500);  
            }  
        }  
 
 
        function OnClientFileOpen(sender, args) {  
            LogEvent("Item open: " + args.get_item().get_name());  
        }  
 
        function LogEvent(text) {  
            var d = new Date();  
            var ddateStr = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();  
            var eventConsole = $get("eventConsole");  
            eventConsole.innerHTML += "[" + dateStr + "] " + text + "<br/>";  
        }  
 
        function OnClientFileOpen(oExplorer, args) {  
            debugger;  
            var item = args.get_item();  
            var fileExtension = item.get_extension();  
 
            //var fileDownloadMode = document.getElementById("chkbxDownoaldFile").checked;  
            if ((fileExtension == "jpg" || fileExtension == "gif") && fileExtension == "xlsx" || fileExtension == "docx") {// Download the file   
                // File is a image document, do not open a new window  
                args.set_cancel(true);  
 
                // Tell browser to open file directly  
                var requestImage = "FileSystemHandler.ashx?path=" + item.get_url();  
                document.location = requestImage;  
            //}  
        }  
 


Please help me to solve my problem .

Thanks & Regards

Ajay Jamwal 

1 Answer, 1 is accepted

Sort by
0
Accepted
Fiko
Telerik team
answered on 06 Oct 2009, 04:50 PM
Hi Ajay,

I believe that the information in this KB article will be of help.

All the best,
Fiko
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Tags
FileExplorer
Asked by
Ajay
Top achievements
Rank 2
Answers by
Fiko
Telerik team
Share this question
or