Commit 2110d805 authored by SergeevaAA's avatar SergeevaAA

Реализована загрузка файлов

parent ef41611b
// <auto-generated />
using System;
using FileDesk.DataAccess.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace FileDesk.DataAccess.Migrations
{
[DbContext(typeof(FileDeskContext))]
[Migration("20201029080153_AddSizeFieldInFilesTable")]
partial class AddSizeFieldInFilesTable
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("FileDesk.Domain.Models.Action", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("ActionType")
.HasColumnType("int");
b.Property<DateTime>("DateTime")
.HasColumnType("datetime2");
b.Property<long>("FileId")
.HasColumnType("bigint");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("FileId");
b.HasIndex("UserId");
b.ToTable("Actions");
});
modelBuilder.Entity("FileDesk.Domain.Models.Contact", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Department")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("MiddleName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Organization")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Phone")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Post")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Contacts");
b.HasData(
new
{
Id = 1L,
Department = "ИШИТР",
Email = "aas189@tpu.ru",
FirstName = "Анастасия",
LastName = "Сергеева",
MiddleName = "Анатольевна",
Organization = "ТПУ",
Phone = "+7(987)654-32-10",
Post = "Студент группы 8ИМ91"
});
});
modelBuilder.Entity("FileDesk.Domain.Models.File", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("varbinary(max)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Format")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<long>("Size")
.HasColumnType("bigint");
b.Property<DateTime>("UploadDateTime")
.HasColumnType("datetime2");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Files");
});
modelBuilder.Entity("FileDesk.Domain.Models.Role", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Roles");
b.HasData(
new
{
Id = 1L,
Name = "admin"
},
new
{
Id = 2L,
Name = "user"
});
});
modelBuilder.Entity("FileDesk.Domain.Models.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Login")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("Login")
.IsUnique();
b.ToTable("Users");
b.HasData(
new
{
Id = 1L,
Login = "admin",
Password = "5EBE2294ECD0E0F08EAB7690D2A6EE69"
},
new
{
Id = 2L,
Login = "user",
Password = "93AB957B29BBD2564F1850110F29120D"
});
});
modelBuilder.Entity("FileDesk.Domain.Models.UserRole", b =>
{
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<long>("RoleId")
.HasColumnType("bigint");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("UserRoles");
b.HasData(
new
{
UserId = 1L,
RoleId = 1L
},
new
{
UserId = 1L,
RoleId = 2L
},
new
{
UserId = 2L,
RoleId = 2L
});
});
modelBuilder.Entity("FileDesk.Domain.Models.Action", b =>
{
b.HasOne("FileDesk.Domain.Models.File", "File")
.WithMany("Actions")
.HasForeignKey("FileId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FileDesk.Domain.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("FileDesk.Domain.Models.File", b =>
{
b.HasOne("FileDesk.Domain.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("FileDesk.Domain.Models.UserRole", b =>
{
b.HasOne("FileDesk.Domain.Models.Role", "Role")
.WithMany("UserRoles")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FileDesk.Domain.Models.User", "User")
.WithMany("UserRoles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
namespace FileDesk.DataAccess.Migrations
{
public partial class AddSizeFieldInFilesTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<long>(
name: "Size",
table: "Files",
nullable: false,
defaultValue: 0L);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Size",
table: "Files");
}
}
}
......@@ -126,6 +126,9 @@ namespace FileDesk.DataAccess.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<long>("Size")
.HasColumnType("bigint");
b.Property<DateTime>("UploadDateTime")
.HasColumnType("datetime2");
......@@ -242,7 +245,7 @@ namespace FileDesk.DataAccess.Migrations
modelBuilder.Entity("FileDesk.Domain.Models.Action", b =>
{
b.HasOne("FileDesk.Domain.Models.File", "File")
.WithMany()
.WithMany("Actions")
.HasForeignKey("FileId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
......
namespace FileDesk.Domain.Enums
{
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Формат файла
/// </summary>
......@@ -8,46 +10,43 @@
/// <summary>
/// Неизвестный формат
/// </summary>
[Display(Name = "Неизвестный формат")]
Unknown = 0,
/// <summary>
/// Текстовый файл
/// </summary>
PlainText = 1,
/// <summary>
/// Файл MS Word
/// </summary>
Word = 2,
[Display(Name = "Текстовый файл")]
Text = 1,
/// <summary>
/// Файл MS Excel
/// Документ
/// </summary>
Excel = 3,
[Display(Name = "Документ")]
Document = 2,
/// <summary>
/// Файл MS PowerPoint
/// Изображение
/// </summary>
PowerPoint = 4,
[Display(Name = "Изображение")]
Picture = 3,
/// <summary>
/// Графический файл
/// </summary>
Picture = 5,
/// <summary>
/// Pdf-файл
/// Аудиофайл
/// </summary>
Pdf = 6,
[Display(Name = "Аудиофайл")]
Audio = 4,
/// <summary>
/// Аудиофайл
/// Видеофайл
/// </summary>
Music = 7,
[Display(Name = "Видеофайл")]
Video = 5,
/// <summary>
/// Видеофайл
/// Исполняемый файл
/// </summary>
Video = 8
[Display(Name = "Исполняемый файл")]
Executed = 6
}
}
\ No newline at end of file
......@@ -5,6 +5,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="3.1.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
</ItemGroup>
......
namespace FileDesk.Domain.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using FileDesk.Domain.Enums;
......@@ -50,5 +51,16 @@
/// Пользователь
/// </summary>
public virtual User User { get; set; }
/// <summary>
/// Размер в байтах
/// </summary>
[Required]
public virtual long Size { get; set; }
/// <summary>
/// Действия с файлом
/// </summary>
public virtual List<Action> Actions { get; set; } = new List<Action>();
}
}
\ No newline at end of file
namespace FileDesk.Domain.ViewModels
{
using Microsoft.AspNetCore.Http;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Вью-модель файла для загрузки
/// </summary>
public class UploadViewModel
{
/// <summary>
/// Название
/// </summary>
[Required]
[DisplayName("Название")]
public virtual string Name { get; set; }
/// <summary>
/// Описание
/// </summary>
[Required]
[DisplayName("Описание")]
public virtual string Description { get; set; }
/// <summary>
/// Файл
/// </summary>
[Required]
[DisplayName("Файл")]
public virtual IFormFile File { get; set; }
}
}
\ No newline at end of file
namespace FileDesk.Services
{
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Http;
using FileDesk.DataAccess.Repository;
using FileDesk.Domain.Enums;
using FileDesk.Domain.ViewModels;
using FileDesk.Services.Interfaces;
using Action = Domain.Models.Action;
using File = Domain.Models.File;
using Microsoft.EntityFrameworkCore;
using System.Linq;
/// <summary>
/// Сервис для работы с файлами
/// </summary>
public class FileService : IFileService
{
private readonly FileDeskContext _db;
/// <summary>
/// Создает новый экземпляр класса <see cref = "FileService"/>
/// </summary>
/// <param name="db">Контекст для работы с БД</param>
public FileService(FileDeskContext db)
{
_db = db;
}
/// <summary>
/// Загрузка файла
/// </summary>
/// <param name="file">Файл</param>
/// <returns></returns>
public void Upload(long userId, UploadViewModel file)
{
var currentDateTime = DateTime.Now;
_db.Files.Add(new File
{
UserId = userId,
UploadDateTime = currentDateTime,
Name = $"{file.Name}{Path.GetExtension(file.File.FileName)}",
Description = file.Description,
Content = GetContent(file.File),
Format = GetFormat(file.File.FileName),
Size = file.File.Length,
Actions = new List<Action>
{
new Action
{
UserId = userId,
DateTime = currentDateTime,
ActionType = ActionType.Upload
}
}
});
_db.SaveChanges();
}
/// <summary>
/// Получение формата файла
/// </summary>
/// <param name="fileName">Название файла</param>
/// <returns></returns>
private FileFormat GetFormat(string fileName)
{
switch (Path.GetExtension(fileName))
{
case ".log":
case ".txt":
return FileFormat.Text;
case ".doc":
case ".docm":
case ".docx":
case ".dot":
case ".dotm":
case ".dotx":
case ".pdf":
case ".ppt":
case ".pptm":
case ".pptx":
case ".pot":
case ".potm":
case ".potx":
case ".pps":
case ".ppsm":
case ".ppsx":
case ".xls":
case ".xlsb":
case ".xlsm":
case ".xlsx":
case ".xlt":
case ".xltm":
case ".xltx":
case ".rtf":
return FileFormat.Document;
case ".ico":
case ".png":
case ".svg":
case ".bmp":
case ".gif":
case ".jpeg":
case ".jpg":