gpt4 book ai didi

Angular 6 清理本地驱动器 url

转载 作者:行者123 更新时间:2023-12-04 12:13:34 26 4
gpt4 key购买 nike

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

C:\path\to\executable

有没有办法清理这个 url 以用作 href 值?

此外,我将值与 [] 符号绑定(bind),因此我确定它不会作为字符串插入。

最佳答案

首先网址应该是 C:/path/to/executable不是那个 C:\path\to\executable
根据 http://www.ietf.org/rfc/rfc2396.txt反斜杠字符不是 URL 中的有效字符

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

现在关于 sanitizer

您可以使用 bypassSecurityTrustUrl() 绑定(bind)一个返回安全 url 的函数。 Angular DomSanitizer

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 中注入(inject)这个管道服务
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

关于Angular 6 清理本地驱动器 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com