保护上传的图像/文件的访问权限是一种常见的需求,可以使用Angular和Node.js来实现。以下是一种解决方案,其中包含代码示例:
Angular端代码:
import { Injectable } from '@angular/core';
import import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class FileService {
  constructor(private http: HttpClient) { }
  uploadFile(file: File): Observable {
    const formData = new FormData();
    formData.append('file', file);
    return this.http.post('http://localhost:3000/upload', formData);
  }
  getFile(filename: string): Observable {
    const headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('token'));
    return this.http.get('http://localhost:3000/files/' + filename, { headers });
  }
}
    
import { Component } from '@angular/core';
import { FileService } from './file.service';
@Component({
  selector: 'app-upload',
  template: `
    
    
  `
})
export class UploadComponent {
  selectedFile: File;
  constructor(private fileService: FileService) { }
  onFileSelected(files: FileList) {
    this.selectedFile = files.item(0);
  }
  uploadFile() {
    this.fileService.uploadFile(this.selectedFile).subscribe(
      result => {
        console.log('File uploaded successfully');
      },
      error => {
        console.error('Error uploading file:', error);
      }
    );
  }
}
@Component({
  selector: 'app-file',
  template: `
    
    
  `
})
export class FileComponent {
  fileUrl: string;
  constructor(private fileService: FileService) { }
  getFile() {
    this.fileService.getFile('example.jpg').subscribe(
      result => {
        this.fileUrl = result.url;
      },
      error => {
        console.error('Error getting file:', error);
      }
    );
  }
}
Node.js端代码:
const express = require('express');
const app = express();
const multer = require('multer');
const path = require('path');
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  }
});
const upload = multer({ storage });
app.post('/upload', upload.single('file'), (req, res) => {
  res.json({ message: 'File uploaded successfully' });
});
app.get('/files/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = path.join(__dirname, 'uploads', filename);
  // Check access permissions here before sending the file
  res.sendFile(filePath);
});
app.listen(3000, () => {
  console.log('Server started on port 3000');
});
请注意,上述代码仅提供了一个基本的示例,实际应用中还需要添加更多的逻辑来确保安全性和可靠性。