added image preview to the file manager component

This commit is contained in:
Shaun Walker 2020-02-22 09:56:28 -05:00
parent 74d4b6412e
commit 00914208ba
12 changed files with 164 additions and 88 deletions

View File

@ -11,7 +11,7 @@
<label for="Name" class="control-label">Module: </label>
</td>
<td>
<FileManager Filter=".nupkg" ShowFiles="false" Folder="Modules" />
<FileManager Filter="nupkg" ShowFiles="false" Folder="Modules" />
</td>
</tr>
</table>

View File

@ -11,7 +11,7 @@
<label for="Name" class="control-label">Theme: </label>
</td>
<td>
<FileManager Filter=".nupkg" ShowFiles="false" Folder="Themes" />
<FileManager Filter="nupkg" ShowFiles="false" Folder="Themes" />
</td>
</tr>
</table>

View File

@ -11,7 +11,7 @@
<label for="Name" class="control-label">Framework: </label>
</td>
<td>
<FileManager Filter=".nupkg" ShowFiles="false" Folder="Framework" />
<FileManager Filter="nupkg" ShowFiles="false" Folder="Framework" />
</td>
</tr>
</table>

View File

@ -6,60 +6,72 @@
@if (folders != null)
{
<select class="form-control" @onchange="(e => FolderChanged(e))">
@if (string.IsNullOrEmpty(Folder))
{
<option value="-1">&lt;Select Folder&gt;</option>
}
@foreach (Folder folder in folders)
{
if (folder.FolderId == folderid)
{
<option value="@(folder.FolderId)" selected>@(new string('-', folder.Level * 2))@(folder.Name)</option>
}
else
{
<option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
}
}
</select>
@if (showfiles)
{
<select class="form-control" @onchange="(e => FileChanged(e))">
<option value="-1">&lt;Select File&gt;</option>
@foreach (File file in files)
{
if (file.FileId == fileid)
<div class="container-fluid">
<div class="row">
<div class="col">
<select class="form-control" @onchange="(e => FolderChanged(e))">
@if (string.IsNullOrEmpty(Folder))
{
<option value="-1">&lt;Select Folder&gt;</option>
}
@foreach (Folder folder in folders)
{
if (folder.FolderId == folderid)
{
<option value="@(folder.FolderId)" selected>@(new string('-', folder.Level * 2))@(folder.Name)</option>
}
else
{
<option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
}
}
</select>
@if (showfiles)
{
<option value="@(file.FileId)" selected>@(file.Name)</option>
<select class="form-control" @onchange="(e => FileChanged(e))">
<option value="-1">&lt;Select File&gt;</option>
@foreach (File file in files)
{
if (file.FileId == fileid)
{
<option value="@(file.FileId)" selected>@(file.Name)</option>
}
else
{
<option value="@(file.FileId)">@(file.Name)</option>
}
}
</select>
}
else
@if (haseditpermission)
{
<option value="@(file.FileId)">@(file.Name)</option>
<div>
@if (uploadmultiple)
{
<input type="file" id="@fileinputid" name="file" accept="@filter" multiple />
}
else
{
<input type="file" id="@fileinputid" name="file" accept="@filter" />
}
<span id="@progressinfoid"></span> <progress id="@progressbarid" style="visibility: hidden;"></progress>
@if (showfiles && GetFileId() != -1)
{
<button type="button" class="btn btn-danger float-right" @onclick="DeleteFile">Delete</button>
}
<button type="button" class="btn btn-success float-right" @onclick="UploadFile">Upload</button>
</div>
@((MarkupString)@message)
}
}
</select>
}
@if (haseditpermission)
{
<div>
@if (uploadmultiple)
{
<input type="file" id="@fileinputid" name="file" accept="@filter" multiple />
}
else
{
<input type="file" id="@fileinputid" name="file" accept="@filter" />
}
<span id="@progressinfoid"></span> <progress id="@progressbarid" style="visibility: hidden;"></progress>
@if (showfiles && GetFileId() != -1)
{
<button type="button" class="btn btn-danger float-right" @onclick="DeleteFile">Delete</button>
}
<button type="button" class="btn btn-success float-right" @onclick="UploadFile">Upload</button>
</div>
<div class="col-auto">
@if (@image != "")
{
@((MarkupString)@image)
}
</div>
</div>
@((MarkupString)@message)
}
</div>
}
@code {
@ -76,11 +88,12 @@
public string FileId { get; set; } // optional - for setting a specific file by default
[Parameter]
public string Filter { get; set; } // optional - comma delimited list of file types that can be selected or uploaded ie. ".jpg,.gif"
public string Filter { get; set; } // optional - comma delimited list of file types that can be selected or uploaded ie. "jpg,gif"
[Parameter]
public string UploadMultiple { get; set; } // optional - enable multiple file uploads - default false
string id;
List<Folder> folders;
int folderid = -1;
@ -94,6 +107,7 @@
bool uploadmultiple = false;
bool haseditpermission = false;
string message = "";
string image = "";
protected override async Task OnInitializedAsync()
{
@ -115,6 +129,7 @@
if (!string.IsNullOrEmpty(FileId))
{
fileid = int.Parse(FileId);
await SetImage();
if (fileid != -1)
{
File file = await FileService.GetFileAsync(int.Parse(FileId));
@ -131,7 +146,7 @@
if (!string.IsNullOrEmpty(Filter))
{
filter = Filter;
filter = "." + Filter.Replace(",",",.");
}
await GetFiles();
@ -184,7 +199,7 @@
}
}
private async void FolderChanged(ChangeEventArgs e)
private async Task FolderChanged(ChangeEventArgs e)
{
message = "";
try
@ -192,6 +207,7 @@
folderid = int.Parse((string)e.Value);
await GetFiles();
fileid = -1;
image = "";
StateHasChanged();
}
catch (Exception ex)
@ -201,13 +217,36 @@
}
}
private void FileChanged(ChangeEventArgs e)
private async Task FileChanged(ChangeEventArgs e)
{
message = "";
fileid = int.Parse((string)e.Value);
await SetImage();
StateHasChanged();
}
private async Task SetImage()
{
image = "";
if (fileid != -1)
{
File file = await FileService.GetFileAsync(fileid);
if (file.ImageHeight != 0 && file.ImageWidth != 0)
{
int maxwidth = 200;
int maxheight = 200;
double ratioX = (double)maxwidth / (double)file.ImageWidth;
double ratioY = (double)maxheight / (double)file.ImageHeight;
double ratio = ratioX < ratioY ? ratioX : ratioY;
image = "<img src=\"" + ContentUrl(fileid) + "\" alt=\"" + file.Name +
"\" width=\"" + Convert.ToInt32(file.ImageWidth * ratio).ToString() +
"\" height=\"" + Convert.ToInt32(file.ImageHeight * ratio).ToString() + "\" />";
}
}
}
private async Task UploadFile()
{
var interop = new Interop(jsRuntime);
@ -236,6 +275,7 @@
if (file != null)
{
fileid = file.FileId;
await SetImage();
}
}
StateHasChanged();
@ -268,6 +308,7 @@
message = "<br /><div class=\"alert alert-success\" role=\"alert\">File Deleted</div>";
await GetFiles();
fileid = -1;
await SetImage();
StateHasChanged();
}
catch (Exception ex)

View File

@ -4,11 +4,17 @@
@if (filemanagervisible)
{
<FileManager @ref="filemanager" Filter=".jpg,.jpeg,.jpe,.gif,.png" />
<FileManager @ref="filemanager" Filter="@Constants.ImageFiles" />
@((MarkupString)@message)
<br />
}
<div class="row justify-content-center">
<button type="button" class="btn btn-success" @onclick="InsertImage">Insert Image</button>
@if (filemanagervisible)
{
@((MarkupString)"&nbsp;&nbsp;")
<button type="button" class="btn btn-secondary" @onclick="CloseFileManager">Close</button>
}
</div>
<br />
<div @ref="@ToolBar">
@ -114,4 +120,12 @@
}
StateHasChanged();
}
public async Task CloseFileManager()
{
filemanagervisible = false;
message = "";
StateHasChanged();
}
}

View File

@ -13,6 +13,7 @@ using System.Threading;
using System.Threading.Tasks;
using Oqtane.Security;
using System.Linq;
using System.Drawing;
namespace Oqtane.Controllers
{
@ -25,7 +26,6 @@ namespace Oqtane.Controllers
private readonly IUserPermissions UserPermissions;
private readonly ITenantResolver Tenants;
private readonly ILogManager logger;
private readonly string WhiteList = "jpg,jpeg,jpe,gif,bmp,png,mov,wmv,avi,mp4,mp3,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,zip,nupkg";
public FileController(IWebHostEnvironment environment, IFileRepository Files, IFolderRepository Folders, IUserPermissions UserPermissions, ITenantResolver Tenants, ILogManager logger)
{
@ -139,16 +139,23 @@ namespace Oqtane.Controllers
string folderpath = GetFolderPath(folder);
CreateDirectory(folderpath);
string filename = url.Substring(url.LastIndexOf("/") + 1);
try
// check for allowable file extensions
if (Constants.UploadableFiles.Contains(Path.GetExtension(filename).Replace(".", "")))
{
var client = new System.Net.WebClient();
client.DownloadFile(url, folderpath + filename);
FileInfo fileinfo = new FileInfo(folderpath + filename);
file = Files.AddFile(new Models.File { Name = filename, FolderId = folder.FolderId, Extension = fileinfo.Extension.Replace(".",""), Size = (int)fileinfo.Length });
try
{
var client = new System.Net.WebClient();
client.DownloadFile(url, folderpath + filename);
Files.AddFile(CreateFile(filename, folder.FolderId, folderpath + filename));
}
catch
{
logger.Log(LogLevel.Error, this, LogFunction.Create, "File Could Not Be Downloaded From Url {Url}", url);
}
}
catch
else
{
logger.Log(LogLevel.Error, this, LogFunction.Create, "File Could Not Be Downloaded From Url {Url}", url);
logger.Log(LogLevel.Error, this, LogFunction.Create, "File Could Not Be Downloaded From Url Due To Its File Extension {Url}", url);
}
}
else
@ -193,8 +200,7 @@ namespace Oqtane.Controllers
string upload = await MergeFile(folderpath, file.FileName);
if (upload != "" && folderid != -1)
{
FileInfo fileinfo = new FileInfo(folderpath + upload);
Files.AddFile(new Models.File { Name = upload, FolderId = folderid, Extension = fileinfo.Extension.Replace(".", ""), Size = (int)fileinfo.Length });
Files.AddFile(CreateFile(upload, folderid, folderpath + upload));
}
}
else
@ -248,7 +254,7 @@ namespace Oqtane.Controllers
}
// check for allowable file extensions
if (!WhiteList.Contains(Path.GetExtension(filename).Replace(".", "")))
if (!Constants.UploadableFiles.Contains(Path.GetExtension(filename).Replace(".", "")))
{
System.IO.File.Delete(Path.Combine(folder, filename + ".tmp"));
}
@ -357,5 +363,31 @@ namespace Oqtane.Controllers
}
}
}
private Models.File CreateFile(string filename, int folderid, string filepath)
{
Models.File file = new Models.File();
file.Name = filename;
file.FolderId = folderid;
FileInfo fileinfo = new FileInfo(filepath);
file.Extension = fileinfo.Extension.ToLower().Replace(".", "");
file.Size = (int)fileinfo.Length;
file.ImageHeight = 0;
file.ImageWidth = 0;
if (Constants.ImageFiles.Contains(file.Extension))
{
FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
using (var image = Image.FromStream(stream))
{
file.ImageHeight = image.Height;
file.ImageWidth = image.Width;
}
stream.Close();
}
return file;
}
}
}

View File

@ -44,6 +44,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc3" />
<PackageReference Include="System.Drawing.Common" Version="4.7.0" />
</ItemGroup>
<ItemGroup>

View File

@ -176,7 +176,7 @@ namespace Oqtane.Repository
FolderRepository.AddFolder(new Folder { SiteId = site.SiteId, ParentId = folder.FolderId, Name = "Users", Path = "Users\\", Order = 1, IsSystem = true, Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"Administrators\"},{\"PermissionName\":\"View\",\"Permissions\":\"Administrators\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"Administrators\"}]" });
if (site.Name == "Default Site")
{
File file = FileRepository.AddFile(new File { FolderId = folder.FolderId, Name = "logo.png", Extension = "png", Size = 8192 });
File file = FileRepository.AddFile(new File { FolderId = folder.FolderId, Name = "logo.png", Extension = "png", Size = 8192, ImageHeight = 80, ImageWidth = 250 });
site.LogoFileId = file.FileId;
UpdateSite(site);
}

View File

@ -285,6 +285,8 @@ CREATE TABLE [dbo].[File](
[Name] [nvarchar](250) NOT NULL,
[Extension] [nvarchar](50) NOT NULL,
[Size] [int] NOT NULL,
[ImageHeight] [int] NOT NULL,
[ImageWidth] [int] NOT NULL,
[CreatedBy] [nvarchar](256) NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[ModifiedBy] [nvarchar](256) NOT NULL,

View File

@ -9,6 +9,8 @@ namespace Oqtane.Models
public string Name { get; set; }
public string Extension { get; set; }
public int Size { get; set; }
public int ImageHeight { get; set; }
public int ImageWidth { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }

View File

@ -1,5 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace Oqtane.Models
{
@ -21,23 +20,5 @@ namespace Oqtane.Models
public string DeletedBy { get; set; }
public DateTime? DeletedOn { get; set; }
public bool IsDeleted { get; set; }
[NotMapped]
public string TenantRootPath
{
get
{
return "Tenants/" + TenantId.ToString() + "/";
}
}
[NotMapped]
public string SiteRootPath
{
get
{
return "Tenants/" + TenantId.ToString() + "/Sites/" + SiteId.ToString() + "/";
}
}
}
}

View File

@ -31,5 +31,8 @@
public const string HostRole = "Host Users";
public const string AdminRole = "Administrators";
public const string RegisteredRole = "Registered Users";
public const string ImageFiles = "jpg,jpeg,jpe,gif,bmp,png";
public const string UploadableFiles = "jpg,jpeg,jpe,gif,bmp,png,mov,wmv,avi,mp4,mp3,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,zip,nupkg";
}
}