You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中带JWT请求获取视频附件失败问题求助

Troubleshooting Video Attachment Loading in Angular SecurePipe

Hey there! Let's figure out why your video attachments aren't loading even though images work perfectly. Here are targeted fixes and debugging steps to resolve this:

1. Double-Check JWT Token Inclusion for Video Requests

Even though images load, it’s possible your video requests aren’t properly carrying the JWT token (maybe your interceptor skips certain URL patterns, or the backend enforces stricter validation for videos). Update your SecurePipe to explicitly attach the authorization header:

import { HttpHeaders } from '@angular/common/http';

@Pipe({ name: 'secure' })
export class SecurePipe implements PipeTransform {
 constructor(
   private http: HttpClient, 
   private sanitizer: DomSanitizer,
   private authService: YourAuthService // Replace with your token service
 ) { }

 transform(url): Observable<SafeUrl> {
  const authHeader = new HttpHeaders().set(
    'Authorization', 
    `Bearer ${this.authService.getAuthToken()}`
  );
  
  return this.http
   .get(url, { responseType: 'blob', headers: authHeader })
   .map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));
 }
}

2. Fix Video Blob MIME Type Handling

Browsers require precise MIME types to render videos. If the returned blob lacks a valid video/mp4 type, the video element will fail to process it. Modify your pipe to enforce the correct MIME type:

.map((blob: Blob) => {
  // Explicitly set MIME type if the blob's type is missing or incorrect
  const validVideoBlob = new Blob([blob], { 
    type: blob.type || 'video/mp4' 
  });
  return this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(validVideoBlob));
})

3. Add Cross-Origin Attribute to the Video Element

If your video is hosted on a different domain, CORS restrictions might block it. Add the crossorigin attribute to your video tag:

<video *ngIf="file?.type?.toString()?.includes('video')" 
       height="70px" width="70px" 
       [src]="file?.source | secure | async" 
       crossorigin="anonymous"
       (loadedmetadata)="getDuration($event, i)">
</video>

Ensure your backend also allows cross-origin requests for video files (verify headers like Access-Control-Allow-Origin are set correctly).

4. Debug the Request/Response Flow

Add logging to your pipe to pinpoint where things go wrong. This will help you confirm if the issue is with authentication, data retrieval, or blob processing:

import { tap } from 'rxjs/operators';

return this.http.get(url, { responseType: 'blob', observe: 'response' })
 .pipe(
   tap(response => {
     console.log('Video Request URL:', url);
     console.log('Response Status:', response.status);
     console.log('Backend Content-Type:', response.headers.get('Content-Type'));
     console.log('Blob Size (bytes):', response.body.size);
   }),
   map(response => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(response.body)))
 );

Check your browser console for these clues:

  • 401 Unauthorized: JWT token is missing or invalid
  • 200 OK with application/octet-stream: Backend isn’t returning the correct video MIME type
  • Matching blob size to your video file: Data is fetched, but the video element can’t parse it (likely a MIME type issue)

5. Handle Large Videos with Timeouts

Videos are often larger than images, so your request might be timing out. Add a timeout to your HTTP call:

import { timeout } from 'rxjs/operators';

return this.http.get(url, { responseType: 'blob', headers: authHeader })
 .pipe(
   timeout(30000), // 30-second timeout (adjust as needed)
   map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)))
 );

内容的提问来源于stack exchange,提问作者Ihssane Hanzaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:22:51