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

如何用Angular 4调用摄像头录制音视频并发送至Spring Boot后端存储?

Is It Feasible to Record Audio/Video with Angular 4 & Store via Spring?

Absolutely feasible! I’ve helped build similar workflows before, so let’s break down exactly how to pull this off step by step.

Angular 4 Frontend Implementation

Angular 4 can tap into the browser’s native Media APIs to access cameras/microphones and record media. Here’s a practical approach:

1. Request Permissions & Access Media Streams

First, you need user consent to access their camera and microphone. Use the navigator.mediaDevices API for this:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-media-recorder',
  templateUrl: './media-recorder.component.html'
})
export class MediaRecorderComponent {
  mediaRecorder: MediaRecorder;
  recordedBlobs: Blob[] = [];
  stream: MediaStream;

  constructor(private http: HttpClient) {}

  async startRecording() {
    try {
      // Request access to camera + microphone (set video: false for audio-only)
      this.stream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true
      });

      // Initialize recorder with the media stream
      this.mediaRecorder = new MediaRecorder(this.stream);
      this.mediaRecorder.ondataavailable = (event) => {
        if (event.data && event.data.size > 0) {
          this.recordedBlobs.push(event.data);
        }
      };

      this.mediaRecorder.start();
      console.log('Recording started');
    } catch (err) {
      console.error('Failed to access media devices:', err);
    }
  }
}

2. Stop Recording & Upload to Spring

Add methods to stop recording, package the media into a file, and send it to your backend:

stopRecording() {
  this.mediaRecorder.stop();
  this.stream.getTracks().forEach(track => track.stop()); // Release camera/mic resources
  console.log('Recording stopped');

  // Combine recorded chunks into a single Blob
  const blob = new Blob(this.recordedBlobs, { type: 'video/webm' }); // Use 'audio/wav' for audio-only
  this.uploadMedia(blob);
}

uploadMedia(blob: Blob) {
  const formData = new FormData();
  formData.append('mediaFile', blob, `recorded-${Date.now()}.webm`); // Add timestamp to avoid filename conflicts

  // Send to Spring endpoint
  this.http.post('http://your-spring-server:8080/upload', formData)
    .subscribe({
      next: (res) => console.log('Upload successful:', res),
      error: (err) => console.error('Upload failed:', err)
    });
}

Don’t forget to import HttpClientModule in your Angular app module to enable HTTP requests.

Key Frontend Notes

  • HTTPS Requirement: Browsers require HTTPS (or localhost for development) to access media devices.
  • Browser Compatibility: MediaRecorder works in most modern browsers, but add fallback logic if you need to support older versions.
  • Audio-Only Adjustment: Set video: false in getUserMedia and change the Blob type to audio/wav for pure audio recordings.

Spring Backend Implementation

Your Spring app will handle file uploads and store the media. Here’s how to set this up:

1. Configure Multipart Support

Add these lines to application.properties to allow large file uploads:

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

2. Create an Upload Endpoint

Write a controller to receive and store the media file:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
public class MediaUploadController {

    // Update this path to your preferred storage directory
    private final String STORAGE_DIR = "/opt/app/media-storage/";

    @PostMapping("/upload")
    public ResponseEntity<String> uploadMedia(@RequestParam("mediaFile") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("Uploaded file is empty", HttpStatus.BAD_REQUEST);
        }

        try {
            // Create storage directory if it doesn't exist
            Path storagePath = Paths.get(STORAGE_DIR);
            if (!Files.exists(storagePath)) {
                Files.createDirectories(storagePath);
            }

            // Save the file to disk
            Path filePath = storagePath.resolve(file.getOriginalFilename());
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            return new ResponseEntity<>("File stored successfully: " + file.getOriginalFilename(), HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>("Failed to store file: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

3. Enable Cross-Origin Requests (CORS)

If your Angular app runs on a different port/domain, add CORS configuration to allow requests:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:4200"); // Replace with your Angular app URL
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

Final Tips

  • Production Considerations: For production, add file type validation (e.g., only allow webm/wav files) and consider using cloud storage (like AWS S3) instead of local disk.
  • Testing: Test the full flow—start recording, stop, upload, and verify the file appears in your storage directory.

Content from Stack Exchange, asked by Priyatham Krishna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:09:31