首页 > 解决方案 > 无法从数据库上传和检索文件

问题描述

服务器.component.html

<label for="user_data">Upload file</label>
      <input type="file" multiple formControlName="file" class="form-control" id="file" (change)=uploadFile($event) accept=".pdf,.docx" required>

服务器.component.ts

uploadFile(event) {
        let Sport_files = event.target.files;
        if (Sport_files > 0) {
          console.log(this.sports_videoForm.value.file); // You will see the file link
          this.dataService.uploadFile(this.sports_videoForm.value.file);
        }

SportsData.service.ts(服务组件实现)

uploadFile(file) {
        let formData: FormData = new FormData();
        formData.append('file', file, file.name);

        this.http.post("http://localhost:/4200/", formData)
      }

在培训部分中检索预期课程的文件,sports_training.component.html

<a href="{{item.file}}" target="_blank" class="col-sm-4" style="padding-bottom: 10px">uploaded file</a>

标签: htmltypescriptfirebasefirebase-realtime-databaseangular5

解决方案


您需要使用DomSanitizerbypassSecurityTrustUrl的方法使角度信任 url

您可以在服务中创建一个通用方法,以便在整个应用程序中使用,因为您可能需要在应用程序的多个组件中使用它。

common.service.ts :

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

...

constructor(private domSanitizer: DomSanitizer) {}

sanitize(url: string){
    return this.sanitizer.bypassSecurityTrustUrl(url);
}

sports_training.component.html:

<a [href]="commonService.sanitize(item.file)" target="_blank" class="col-sm-4" style="padding-bottom: 10px">uploaded file</a>

sanitize您也可以在 sports_training 组件中创建方法,但我建议使用公共服务


推荐阅读