Problem in viewing videos in Thymeleaf & Spring

21 views Asked by At

I run many services using docker-compose, I have a service which is responsible for reading and writing video. it write the video in the same project under videos directory. The problem is when the video-streaming service want to views the videos. I try to access these videos but I can not.

This is the controller in the video-streaming service

@GetMapping("/read")
    public String getVideos(Model model) {
        List<Video> videos = videoRepo.findAll();
        List<VideoResource> videoResources = new ArrayList<>();
        List<String>names = new ArrayList<>();
        for(Video video:videos) {
            String path = video.getPath();
            String name = video.getName();
            String getVideoUri = UriComponentsBuilder.fromUriString(FILE_SYSTEM_SERVICE)
                    .queryParam("path", path)
                    .queryParam("name", name)
                    .toUriString();
            ResponseEntity<byte[]> response = restTemplate.getForEntity(getVideoUri, byte[].class);
            if (response.getStatusCode().is2xxSuccessful()) {
                VideoResource videoResource = new VideoResource(response.getBody(), response.getHeaders().getContentType());
                videoResources.add(videoResource);
                names.add(name);
            }
        }
        model.addAttribute("videoResources",videoResources);
        model.addAttribute("names",names);
        return "video-streaming";
    }

This is the view page in the video-streaming service

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Streaming</title>
</head>

<body>
<h2>Video List</h2>

<div th:if="${videoResources}">
    <ul>
        <th:block th:each="video, name : ${videoResources}">
            <p th:text="${video.data.length}"></p><br>
            <p th:text="${video.contentType}"></p><br>

            <li>
                <h3 th:text="${names[name.index]}"></h3>
                <video width="320" height="240" controls>
                    <source th:src="@{'data:' + ${video.contentType} + ';base64,' + #strings.arrayEncode(video.data)}"
                            type="${video.contentType}" />
                    Your browser does not support the video tag.
                </video>
            </li>
        </th:block>
    </ul>
</div>

<div th:unless="${videoResources}">
    <p>No videos available.</p>
</div>
</body>

</html>
```

**and this is the service that read and write the videos**
```
package com.filesystemservice;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
public class FileSystemService {

    @Value("${video.upload.dir:videos}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam String name, @RequestParam String path) {
        try {
            String fileName = name+".mp4";
            String filePath = uploadDir + File.separator + path + File.separator + fileName;
            File destinationDirectory = new File(uploadDir,path);
            if (!destinationDirectory.exists()) {
                destinationDirectory.mkdirs();
            }
            Path destinationFilePath = Path.of(filePath);
            Files.copy(file.getInputStream(), destinationFilePath, StandardCopyOption.REPLACE_EXISTING);
            return ResponseEntity.ok("File uploaded successfully.");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Error uploading file: " + e.getMessage());
        }
    }

    @GetMapping("/get")
    public ResponseEntity<FileSystemResource> getVideo(@RequestParam String path, @RequestParam String name) {
        String videoFilePath = uploadDir + File.separator + path + File.separator + name + ".mp4";
        File videoFile = new File(videoFilePath);

        if (videoFile.exists()) {
            return ResponseEntity.ok()
                    .contentLength(videoFile.length())
                    .body(new FileSystemResource(videoFile));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

}

```


I think the problem is because the videos that I'm trying to access are outside the project structure.

Does anyone know about it!

i try to access the videos that are outside the project structure but it didn't work with me.

0

There are 0 answers