【问题标题】:Angular 6 sanitize local drive urlAngular 6 清理本地驱动器 url
【发布时间】:2019-04-12 19:47:09
【问题描述】:

我曾尝试使用 DomSanitizer 方法清理以下类型的 url,但没有成功

C:\path\to\executable

有什么方法可以清理这个 url 以用作 href 值?

我还用 [] 表示法绑定了该值,所以我确定它不会被插入为字符串。

【问题讨论】:

  • 你能发布一些示例代码吗?

标签: angular angular-dom-sanitizer


【解决方案1】:

首先网址应该是C:/path/to/executable 而不是C:\path\to\executable

根据http://www.ietf.org/rfc/rfc2396.txt,反斜杠字符不是 URL 中的有效字符

大多数浏览器将反斜杠转换为正斜杠。从技术上讲,如果您需要在 URL 中使用反斜杠字符,则需要使用 %5C 对其进行编码。

现在关于消毒

您可以使用 bypassSecurityTrustUrl() 在角度 DomSanitizer 中绑定一个返回安全 url 的函数

app.component.html

<a [href]="getlink()"> link  </a>

app.component.ts

import { DomSanitizer} from '@angular/platform-browser';


export class AppComponent  {
  constructor(private sanitizer:DomSanitizer) {    }
  name = 'Angular';

  getlink():SafeUrl {
      return this.sanitizer.bypassSecurityTrustUrl("C:/path/to/executable");
  }
}

推荐

使用管道: 你可以创建一个管道来禁用 Angular 的内置清理功能

safe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

 public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
            case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
            case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
            case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
            case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
            default: throw new Error(`Invalid safe type specified: ${type}`);
        }
  }
}

注意:不要忘记在你的 app.module.ts 中注入这个管道服务

import { SafePipe } from './shared/safe-url.pipe';


@NgModule({ declarations: [SafePipe],...});

现在您可以使用管道禁用内置清理功能

 <a [href]="'C:/path/to/executable' | safe: 'url'"> link </a>

我建议使用管道,因为代码是可重用的,这里也是工作演示:https://stackblitz.com/edit/angular-vxcvfr

【讨论】:

  • 您能否指定任何详细信息,例如显示的错误消息或链接的用途,您是否正在尝试下载文件添加file:///C:/path/to/executable 可能无济于事,因为 Chrome 不会使用该文件下载本地文件:/ // 协议无论如何(给你一个不允许加载本地资源错误)。您可以查看以下文章:stackoverflow.com/questions/18246053/…
  • 我正在尝试通过 url 运行文件。我正在创建某种内部仪表板应用程序,而当前系统由于古老的原因,旨在使用本地文件工作。大多数文件都位于网络驱动器中,可以在 Internet Explorer 中使用,chrome 依赖并不会真正影响我,因为我的大多数用户将使用 IE 11/Edge。截至错误消息没有,它只是不午餐可执行文件。
【解决方案2】:

我是这样使用的:
在ts文件中。

import { DomSanitizer } from '@angular/platform-browser';
constructor(
        public domSanitizer: DomSanitizer
    ) { }

在 HTML 文件中

<img [src]="domSanitizer.bypassSecurityTrustUrl(pazar.imagedata)" class="zoom">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多