Solution to save a video file using an java api call and play later from the angular application

To save a video file using a Java API and play it later from an Angular application, you'll need to handle both server-side and client-side operations. Here’s a step-by-step approach to achieve this:

Server-Side (Java)

  1. Create a REST API to Upload and Save the Video File

  • Spring Boot Example: Use Spring Boot to create a RESTful API that handles file uploads.

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

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

@RestController
@RequestMapping("/api/videos")
public class VideoController {

    private static final String UPLOAD_DIR = "uploaded_videos/";

    @PostMapping("/upload")
    public ResponseEntity<String> uploadVideo(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
        }

        try {
            File dir = new File(UPLOAD_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            Files.copy(file.getInputStream(), Paths.get(UPLOAD_DIR + file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
            return ResponseEntity.ok("File uploaded successfully");

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed");
        }
    }

    @GetMapping("/download/{filename}")
    public ResponseEntity<byte[]> downloadVideo(@PathVariable String filename) {
        try {
            File file = new File(UPLOAD_DIR + filename);
            byte[] content = Files.readAllBytes(file.toPath());
            return ResponseEntity.ok().body(content);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
}        

Client-Side (Angular)

2. Upload Video File

  • Service: Create a service to handle file upload.

// video.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class VideoService {

  private uploadUrl = 'http://localhost:8080/api/videos/upload';
  private downloadUrl = 'http://localhost:8080/api/videos/download/';

  constructor(private http: HttpClient) { }

  upload(file: File): Observable<any> {
    const formData = new FormData();
    formData.append('file', file);

    return this.http.post(this.uploadUrl, formData);
  }

  download(filename: string): Observable<Blob> {
    return this.http.get(this.downloadUrl + filename, { responseType: 'blob' });
  }
}        

  • Component: Create a component to use the service for file upload and video playback.

// video.component.ts
import { Component } from '@angular/core';
import { VideoService } from './video.service';

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html'
})
export class VideoComponent {
  videoUrl: string | ArrayBuffer | null = null;

  constructor(private videoService: VideoService) { }

  onFileChange(event: any): void {
    const file = event.target.files[0];
    if (file) {
      this.videoService.upload(file).subscribe(response => {
        console.log('File uploaded successfully');
      });
    }
  }

  playVideo(filename: string): void {
    this.videoService.download(filename).subscribe(blob => {
      const url = URL.createObjectURL(blob);
      this.videoUrl = url;
    });
  }
}        

  • Template: Add file input and video player to your component template.

<!-- video.component.html -->
<input type="file" (change)="onFileChange($event)" />
<button (click)="playVideo('your-video-file.mp4')">Play Video</button>
<video *ngIf="videoUrl" controls [src]="videoUrl"></video>        

3. Configure CORS

If your Angular app and Spring Boot backend are hosted on different origins, configure CORS in your Spring Boot application:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200") // Angular app URL
                .allowedMethods("GET", "POST");
    }
}        

To view or add a comment, sign in

More articles by Rashedul Hossain Khan

Insights from the community

Others also viewed

Explore topics