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> <label for="Name" class="control-label">Module: </label>
</td> </td>
<td> <td>
<FileManager Filter=".nupkg" ShowFiles="false" Folder="Modules" /> <FileManager Filter="nupkg" ShowFiles="false" Folder="Modules" />
</td> </td>
</tr> </tr>
</table> </table>

View File

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

View File

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

View File

@ -6,60 +6,72 @@
@if (folders != null) @if (folders != null)
{ {
<select class="form-control" @onchange="(e => FolderChanged(e))"> <div class="container-fluid">
@if (string.IsNullOrEmpty(Folder)) <div class="row">
{ <div class="col">
<option value="-1">&lt;Select Folder&gt;</option> <select class="form-control" @onchange="(e => FolderChanged(e))">
} @if (string.IsNullOrEmpty(Folder))
@foreach (Folder folder in folders) {
{ <option value="-1">&lt;Select Folder&gt;</option>
if (folder.FolderId == folderid) }
{ @foreach (Folder folder in folders)
<option value="@(folder.FolderId)" selected>@(new string('-', folder.Level * 2))@(folder.Name)</option> {
} if (folder.FolderId == folderid)
else {
{ <option value="@(folder.FolderId)" selected>@(new string('-', folder.Level * 2))@(folder.Name)</option>
<option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option> }
} else
} {
</select> <option value="@(folder.FolderId)">@(new string('-', folder.Level * 2))@(folder.Name)</option>
@if (showfiles) }
{ }
<select class="form-control" @onchange="(e => FileChanged(e))"> </select>
<option value="-1">&lt;Select File&gt;</option> @if (showfiles)
@foreach (File file in files)
{
if (file.FileId == fileid)
{ {
<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)
} }
} </div>
</select> <div class="col-auto">
} @if (@image != "")
@if (haseditpermission) {
{ @((MarkupString)@image)
<div> }
@if (uploadmultiple) </div>
{
<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>
@((MarkupString)@message) </div>
}
} }
@code { @code {
@ -76,11 +88,12 @@
public string FileId { get; set; } // optional - for setting a specific file by default public string FileId { get; set; } // optional - for setting a specific file by default
[Parameter] [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] [Parameter]
public string UploadMultiple { get; set; } // optional - enable multiple file uploads - default false public string UploadMultiple { get; set; } // optional - enable multiple file uploads - default false
string id; string id;
List<Folder> folders; List<Folder> folders;
int folderid = -1; int folderid = -1;
@ -94,6 +107,7 @@
bool uploadmultiple = false; bool uploadmultiple = false;
bool haseditpermission = false; bool haseditpermission = false;
string message = ""; string message = "";
string image = "";
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
@ -115,6 +129,7 @@
if (!string.IsNullOrEmpty(FileId)) if (!string.IsNullOrEmpty(FileId))
{ {
fileid = int.Parse(FileId); fileid = int.Parse(FileId);
await SetImage();
if (fileid != -1) if (fileid != -1)
{ {
File file = await FileService.GetFileAsync(int.Parse(FileId)); File file = await FileService.GetFileAsync(int.Parse(FileId));
@ -131,7 +146,7 @@
if (!string.IsNullOrEmpty(Filter)) if (!string.IsNullOrEmpty(Filter))
{ {
filter = Filter; filter = "." + Filter.Replace(",",",.");
} }
await GetFiles(); await GetFiles();
@ -184,7 +199,7 @@
} }
} }
private async void FolderChanged(ChangeEventArgs e) private async Task FolderChanged(ChangeEventArgs e)
{ {
message = ""; message = "";
try try
@ -192,6 +207,7 @@
folderid = int.Parse((string)e.Value); folderid = int.Parse((string)e.Value);
await GetFiles(); await GetFiles();
fileid = -1; fileid = -1;
image = "";
StateHasChanged(); StateHasChanged();
} }
catch (Exception ex) catch (Exception ex)
@ -201,13 +217,36 @@
} }
} }
private void FileChanged(ChangeEventArgs e) private async Task FileChanged(ChangeEventArgs e)
{ {
message = ""; message = "";
fileid = int.Parse((string)e.Value); fileid = int.Parse((string)e.Value);
await SetImage();
StateHasChanged(); 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() private async Task UploadFile()
{ {
var interop = new Interop(jsRuntime); var interop = new Interop(jsRuntime);
@ -236,6 +275,7 @@
if (file != null) if (file != null)
{ {
fileid = file.FileId; fileid = file.FileId;
await SetImage();
} }
} }
StateHasChanged(); StateHasChanged();
@ -268,6 +308,7 @@
message = "<br /><div class=\"alert alert-success\" role=\"alert\">File Deleted</div>"; message = "<br /><div class=\"alert alert-success\" role=\"alert\">File Deleted</div>";
await GetFiles(); await GetFiles();
fileid = -1; fileid = -1;
await SetImage();
StateHasChanged(); StateHasChanged();
} }
catch (Exception ex) catch (Exception ex)

View File

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

View File

@ -13,6 +13,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Oqtane.Security; using Oqtane.Security;
using System.Linq; using System.Linq;
using System.Drawing;
namespace Oqtane.Controllers namespace Oqtane.Controllers
{ {
@ -25,7 +26,6 @@ namespace Oqtane.Controllers
private readonly IUserPermissions UserPermissions; private readonly IUserPermissions UserPermissions;
private readonly ITenantResolver Tenants; private readonly ITenantResolver Tenants;
private readonly ILogManager logger; 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) 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); string folderpath = GetFolderPath(folder);
CreateDirectory(folderpath); CreateDirectory(folderpath);
string filename = url.Substring(url.LastIndexOf("/") + 1); 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(); try
client.DownloadFile(url, folderpath + filename); {
FileInfo fileinfo = new FileInfo(folderpath + filename); var client = new System.Net.WebClient();
file = Files.AddFile(new Models.File { Name = filename, FolderId = folder.FolderId, Extension = fileinfo.Extension.Replace(".",""), Size = (int)fileinfo.Length }); 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 else
@ -193,8 +200,7 @@ namespace Oqtane.Controllers
string upload = await MergeFile(folderpath, file.FileName); string upload = await MergeFile(folderpath, file.FileName);
if (upload != "" && folderid != -1) if (upload != "" && folderid != -1)
{ {
FileInfo fileinfo = new FileInfo(folderpath + upload); Files.AddFile(CreateFile(upload, folderid, folderpath + upload));
Files.AddFile(new Models.File { Name = upload, FolderId = folderid, Extension = fileinfo.Extension.Replace(".", ""), Size = (int)fileinfo.Length });
} }
} }
else else
@ -248,7 +254,7 @@ namespace Oqtane.Controllers
} }
// check for allowable file extensions // 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")); 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" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc3" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc3" />
<PackageReference Include="System.Drawing.Common" Version="4.7.0" />
</ItemGroup> </ItemGroup>
<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\"}]" }); 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") 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; site.LogoFileId = file.FileId;
UpdateSite(site); UpdateSite(site);
} }

View File

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

View File

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

View File

@ -1,5 +1,4 @@
using System; using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace Oqtane.Models namespace Oqtane.Models
{ {
@ -21,23 +20,5 @@ namespace Oqtane.Models
public string DeletedBy { get; set; } public string DeletedBy { get; set; }
public DateTime? DeletedOn { get; set; } public DateTime? DeletedOn { get; set; }
public bool IsDeleted { 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 HostRole = "Host Users";
public const string AdminRole = "Administrators"; public const string AdminRole = "Administrators";
public const string RegisteredRole = "Registered Users"; 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";
} }
} }