|
|
|
|
using Domain.Models.FileUploads;
|
|
|
|
|
using EntityFramework;
|
|
|
|
|
using Infrastructure.Domain;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Domain.Service.FileUpload
|
|
|
|
|
{
|
|
|
|
|
public class FileUploader:DomainService, IFileUploader
|
|
|
|
|
{
|
|
|
|
|
private readonly FireStationDbContext _context;
|
|
|
|
|
public FileUploader(FireStationDbContext context)
|
|
|
|
|
{
|
|
|
|
|
_context = context;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 上传文件
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="files"></param>
|
|
|
|
|
/// <returns>(文件名,上传记录Id,文件路径)</returns>
|
|
|
|
|
public async Task<List<Tuple<string, Guid, string>>> UploadFiles(IFormFileCollection files,int unitId, int uniacid,int groupId)
|
|
|
|
|
{
|
|
|
|
|
var result = new List<Tuple<string, Guid, string>>();
|
|
|
|
|
if (files != null && files.Any())
|
|
|
|
|
{
|
|
|
|
|
foreach (var file in files)
|
|
|
|
|
{
|
|
|
|
|
var contentType = file.ContentType;
|
|
|
|
|
var fileName = file.FileName;
|
|
|
|
|
var fileExtension = Path.GetExtension(fileName);
|
|
|
|
|
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
|
|
|
|
|
var rootPath = Directory.GetCurrentDirectory();
|
|
|
|
|
var directoryPath = Path.Combine(rootPath, "Uploaded");
|
|
|
|
|
if (!Directory.Exists(directoryPath))
|
|
|
|
|
{
|
|
|
|
|
Directory.CreateDirectory(directoryPath);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var newFileName = $"{fileNameWithoutExtension}-{Guid.NewGuid()}{fileExtension}";
|
|
|
|
|
var filePath = Path.Combine(directoryPath, newFileName);
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite,
|
|
|
|
|
FileShare.ReadWrite))
|
|
|
|
|
{
|
|
|
|
|
using (var stream = file.OpenReadStream())
|
|
|
|
|
{
|
|
|
|
|
await stream.CopyToAsync(fileStream);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var uploadedFile = new UploadedFile
|
|
|
|
|
{
|
|
|
|
|
OriginalName = fileName,
|
|
|
|
|
FileName = newFileName,
|
|
|
|
|
ContentType = contentType,
|
|
|
|
|
Extension = fileExtension,
|
|
|
|
|
Path = filePath,
|
|
|
|
|
UploadedTime = DateTime.Now,
|
|
|
|
|
UploadedBy = "",
|
|
|
|
|
};
|
|
|
|
|
await _context.UploadedFiles.AddAsync(uploadedFile);
|
|
|
|
|
await _context.FileUnits.AddAsync(new FileUnit { FileId = uploadedFile.Id, UnitId = unitId,Uniacid=uniacid,GroupId=groupId});
|
|
|
|
|
await _context.SaveChangesAsync();
|
|
|
|
|
result.Add(new Tuple<string, Guid, string>(fileName, uploadedFile.Id, filePath));
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|