我只是显示我的本地网络 PC 电影。在这种情况下,我已将电影封面名称插入为 moviename_cover.jpg,但它没有显示在输出中。我的下面的代码有什么问题
问题
<img src="@GetCoverImageUrl(Path.GetFileNameWithoutExtension(movieFileName))" alt="Movie Cover" class="movie-cover" />
发放方式
// Function to get the cover image URL based on the movie name
private string GetCoverImageUrl(string movieName)
{
// Construct a relative URL for the movie cover image
return $"/MovieCovers/{movieName}_cover.jpg";
}
这是我的整个代码:
@page "/movies"
<h3>Movies</h3>
<div class="movie-container">
@foreach (var movieFileName in GetMovieFiles())
{
<div class="movie-card" style="cursor: pointer;" @onclick="() => OpenLocalPlayer(movieFileName)">
<div class="movie-title">@Path.GetFileNameWithoutExtension(movieFileName)</div>
<img src="@GetCoverImageUrl(Path.GetFileNameWithoutExtension(movieFileName))" alt="Movie Cover" class="movie-cover" />
</div>
}
</div>
<style>
.movie-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.movie-card {
border: 1px solid #ddd;
border-radius: 8px;
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
}
.movie-title {
position: absolute;
top: 0;
left: 0;
width: 100%;
background-color: rgba(255, 255, 255, 0.8);
padding: 8px;
margin: 0;
z-index: 1; /* Ensure the title is above the image */
}
.movie-cover {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 6px;
}
</style>
@code {
private string serverPath = "\\\\192.168.1.6\\Test\\"; // Replace with your actual server path
// Function to get the list of movie files with .mp4 and .mkv format
private IEnumerable<string> GetMovieFiles()
{
try
{
// Get all files with .mp4 and .mkv extension in the specified directory
var movieFiles = Directory.GetFiles(serverPath, "*.mp4")
.Concat(Directory.GetFiles(serverPath, "*.mkv"));
return movieFiles;
}
catch (Exception ex)
{
// Handle any exceptions that may occur during file retrieval
Console.WriteLine($"Error getting movie files: {ex.Message}");
return Enumerable.Empty<string>();
}
}
// Function to open the local player with the selected movie file
private void OpenLocalPlayer(string fileName)
{
try
{
// Combine the server path and file name to get the full path
string fullPath = Path.Combine(serverPath, fileName);
// Open the file with the default associated application
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = fullPath,
UseShellExecute = true
});
}
catch (Exception ex)
{
// Handle any exceptions that may occur during file opening
Console.WriteLine($"Error opening movie: {ex.Message}");
}
}
// Function to get the cover image URL based on the movie name
private string GetCoverImageUrl(string movieName)
{
// Construct a relative URL for the movie cover image
return $"/MovieCovers/{movieName}_cover.jpg";
}
}
您可以检查是否已将图像放入应用程序的 Web 根目录 (wwwroot) 中名为 MovieCovers 的新文件夹中。
然后您可以创建一个字符串来动态设置为 C# 中 imageSource 的值。
<img src="@imageSource" />
@code {
private string? imageSource;
private void ShowImage(string movieName)
{
imageSource = $"/MovieCovers/{movieName}_cover.jpg";
}
}