网页端调用本地应用打开本地文件(PDF、Word、excel、PPT)

一、背景原因

根据浏览器的安全策略,在网页端无法直接打开本地文件,所以需要开发者曲线救国。

二、实现步骤

前期准备:

确保已安装好可以打开文件的应用软件,如,WPS;

把要打开的文件统一放在一个文件夹,如,在D盘创建文件夹【文件夹名】。

  1. 创建Windows应用程序---callexe
cs 复制代码
namespace callexe
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string strNew = args[0].Substring(10);
            string utoSs = System.Web.HttpUtility.UrlDecode(strNew);

            // 直接打开目录
            string v_OpenFolderPath1 = @"D:/文件夹名/";
            string v_OpenFolderPath = string.Concat(v_OpenFolderPath1, utoSs);

            // 直接打开指定的文件
            System.Diagnostics.Process.Start(v_OpenFolderPath);

            Application.Exit();
        }
   }
}
  1. 创建openfile.reg文件。

为了方便编辑文件,先创建openfile.txt文件,编辑完成后修改文件后缀为.reg,然后双击打开。

.reg:windows操作系统的注册表脚本文件。

创建open-exe文件夹并放在D盘,把callexe文件和openfile.reg放在open-exe里面。

cs 复制代码
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\OPENFILE]
@="URL:OPENFILE"
"URL Protocol"="D:\\open-exe\\callexe\\bin\\Debug\\callexe.exe"
[HKEY_CLASSES_ROOT\OPENFILE\DefaultIcon]
@="D:\\open-exe\\callexe\\bin\\Debug\\callexe.exe,1"
[HKEY_CLASSES_ROOT\OPENFILE\shell]
[HKEY_CLASSES_ROOT\OPENFILE\shell\open]
[HKEY_CLASSES_ROOT\OPENFILE\shell\open\command]
@="D:\\open-exe\\callexe\\bin\\Debug\\callexe.exe %1"
  1. 在前端调用
javascript 复制代码
window.open("crealife1:xxx.pdf");

具体原理以后慢慢补充。

相关推荐
William_cl1 小时前
C# ASP.NET Controller 核心:ViewResult 实战指南(return View (model) 全解析)
开发语言·c#·asp.net
周杰伦fans2 小时前
CommunityToolkit.Mvvm(又称MVVM Toolkit) 与 MvvmLight 的核心区别
开发语言·c#·.netcore
William_cl3 小时前
C# ASP.NET Controller 核心:PartialViewResult 实战指南(AJAX 局部刷新全解析)
ajax·c#·asp.net
yue0083 小时前
C# winform窗体换皮肤
c#·image类
曹牧8 小时前
C#:无法从方法组转换为objec
开发语言·c#
刘欣的博客11 小时前
C# 从API接口获取对象而不用先定义对象类
c#·json动态创建对象
Charles_go12 小时前
C#中级、double和decimal有什么区别
开发语言·c#
小熊熊知识库19 小时前
C#接入AI操作步骤详解(deepseek接入)
人工智能·flask·c#
玖笙&19 小时前
✨WPF编程进阶【7.3】集成动画(附源码)
c++·c#·wpf·visual studio
yue00821 小时前
C# 窗体渐变色
开发语言·javascript·c#