You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

322 lines
12 KiB
C#

using DS.Module.Core;
using DS.Module.Core.Data;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Op.Interface;
using DS.WMS.Core.Sys.Entity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using NPOI.HPSF;
using SharpCompress.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace DS.WMS.Core.Op.Method
{
public class OpFileService : IOpFileService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly ISaasDbService saasService;
private readonly IWebHostEnvironment _environment;
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public OpFileService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
_environment = _serviceProvider.GetRequiredService<IWebHostEnvironment>();
}
/// <summary>
/// 添加附件
/// </summary>
/// <param name="file"></param>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult<string>> AddFile(IFormFile file, [FromForm] OpFileReq req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//未上传文件
if (file == null || file.Length == 0)
{
return await Task.FromResult(DataResult<string>.Failed("附件不存在!"));
}
var limitFiles = AppSetting.app<string>(new string[] { "FileSettings", "FileType" });
var originalFilename = file.FileName; // 文件原始名称
var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀
if (!limitFiles.Contains(fileSuffix))
{
return await Task.FromResult(DataResult<string>.Failed("不允许的文件类型!"));
}
var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" });
var relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" });
var dirAbs = string.Empty;
var fileRelaPath = string.Empty;
var fileAbsPath = string.Empty;
if (string.IsNullOrEmpty(basePath))
{
dirAbs = Path.Combine(_environment.WebRootPath, relativePath);
}
else
{
dirAbs = Path.Combine(basePath, relativePath);
}
if (!Directory.Exists(dirAbs))
Directory.CreateDirectory(dirAbs);
// 先存库获取Id
var id = SnowFlakeSingle.Instance.NextId();
var fileSaveName = $"{id}{fileSuffix}".ToLower();
fileRelaPath = Path.Combine(relativePath, fileSaveName).ToLower();
fileAbsPath = Path.Combine(dirAbs, fileSaveName).ToLower();
var newFile = new OpFile
{
Id = id,
FileName = originalFilename,
FilePath = fileRelaPath,
TypeCode = req.TypeCode,
TypeName = req.TypeName,
LinkId = req.LinkId,
};
await tenantDb.Insertable(newFile).ExecuteCommandAsync();
using (var stream = File.Create(fileAbsPath))
{
await file.CopyToAsync(stream);
}
return await Task.FromResult(DataResult<string>.Success(fileRelaPath));
}
/// <summary>
/// 添加附件
/// </summary>
/// <param name="formCollection"></param>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult<string>> AddMultiFiles(IFormCollection formCollection, [FromForm] OpFileReq req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//文件集合
FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
//未上传文件
if (fileCollection == null || fileCollection.Count == 0)
{
return await Task.FromResult(DataResult<string>.Failed("附件不存在!"));
}
var limitFiles = AppSetting.app<string>(new string[] { "FileSettings", "FileType" });
var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" });
var relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" });
foreach (IFormFile file in fileCollection)
{
var originalFilename = file.FileName; // 文件原始名称
var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀
if (!limitFiles.Contains(fileSuffix))
{
return await Task.FromResult(DataResult<string>.Failed("不允许的文件类型!"));
}
var dirAbs = string.Empty;
var fileRelaPath = string.Empty;
var fileAbsPath = string.Empty;
if (string.IsNullOrEmpty(basePath))
{
dirAbs = Path.Combine(_environment.WebRootPath, relativePath);
}
else
{
dirAbs = Path.Combine(basePath, relativePath);
}
if (!Directory.Exists(dirAbs))
Directory.CreateDirectory(dirAbs);
// 先存库获取Id
var id = SnowFlakeSingle.Instance.NextId();
var fileSaveName = $"{id}{fileSuffix}".ToLower();
fileRelaPath = Path.Combine(relativePath, fileSaveName).ToLower();
fileAbsPath = Path.Combine(dirAbs, fileSaveName).ToLower();
var newFile = new OpFile
{
Id = id,
FileName = originalFilename,
FilePath = fileSaveName,
TypeCode = req.TypeCode,
TypeName = req.TypeName,
LinkId = req.LinkId,
};
await tenantDb.Insertable(newFile).ExecuteCommandAsync();
using (var stream = File.Create(fileAbsPath))
{
await file.CopyToAsync(stream);
}
}
return await Task.FromResult(DataResult<string>.Success("批量上传成功"));
//return await Task.FromResult(DataResult<string>.Success(fileRelaPath));
}
/// <summary>
/// 获取业务附件
/// </summary>
/// <param name="id">业务id</param>
/// <returns></returns>
public DataResult<List<OpFileRes>> GetOpFileList(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var users = db.Queryable<SysUser>().Select(x => new { x.Id, x.UserName }).ToList();
var data = tenantDb.Queryable<OpFile>()
.Where(a => a.LinkId == long.Parse(id))
.Select<OpFileRes>()
.Mapper(it =>
{
it.CreateByName = users.Find(x => x.Id == it.CreateBy).UserName;
})
.ToList();
return DataResult<List<OpFileRes>>.Success(data, MultiLanguageConst.DataQuerySuccess);
}
/// <summary>
/// 批量删除附件
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult<string>> BatchDelFiles(IdModel req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
if (req.Ids.Length == 0)
{
return await Task.FromResult(DataResult<string>.Failed("请勾选要删除的附件!"));
}
var fileList = tenantDb.Queryable<OpFile>().Where(x => req.Ids.Contains(x.Id)).ToList();
//删除文件
foreach (var item in fileList)
{
var filePath= Path.Combine(_environment.WebRootPath, item.FilePath);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
await tenantDb.Deleteable(fileList).ExecuteCommandAsync();
return await Task.FromResult(DataResult<string>.Success("删除成功"));
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<IActionResult> DownloadFile(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var opFile = await tenantDb.Queryable<OpFile>().FirstAsync(u => u.Id == long.Parse(id));
if (opFile == null)
{
throw new Exception("文件信息不存在");
}
var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" });
var relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" });
var dirAbs = string.Empty;
var fileRelaPath = string.Empty;
var fileAbsPath = string.Empty;
if (string.IsNullOrEmpty(basePath))
{
dirAbs = Path.Combine(_environment.WebRootPath, relativePath);
}
else
{
dirAbs = Path.Combine(basePath, relativePath);
}
var fileFullPath = Path.Combine(dirAbs, opFile.FilePath);
if (!File.Exists(fileFullPath))
{
throw new Exception("文件信息路径不存在");
}
//var fileName = HttpUtility.UrlEncode(opFile.FileName, Encoding.GetEncoding("UTF-8"));
var fileName = opFile.FileName;
//var result = new FileStreamResult(new FileStream(fileFullPath, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
//return result;
byte[] byteArr = System.IO.File.ReadAllBytes(fileFullPath);
string mimeType = "application/octet-stream";
return new FileContentResult(byteArr, mimeType)
{
FileDownloadName = fileName
};
}
/// <summary>
/// 获取下载文件
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public DataResult<OpFileDownLoadRes> GetOpFileDownLoad(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var opFile = tenantDb.Queryable<OpFile>().First(u => u.Id == long.Parse(id));
if (opFile == null)
{
return DataResult<OpFileDownLoadRes>.Failed("文件信息不存在");
}
var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" });
var relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" });
var dirAbs = string.Empty;
var fileRelaPath = string.Empty;
var fileAbsPath = string.Empty;
if (string.IsNullOrEmpty(basePath))
{
dirAbs = Path.Combine(_environment.WebRootPath, relativePath);
}
else
{
dirAbs = Path.Combine(basePath, relativePath);
}
var fileFullPath = Path.Combine(dirAbs, opFile.FilePath);
if (!File.Exists(fileFullPath))
{
return DataResult<OpFileDownLoadRes>.Failed("文件信息路径不存在");
}
//var fileName = HttpUtility.UrlEncode(opFile.FileName, Encoding.GetEncoding("UTF-8"));
var temp = File.ReadAllBytes(fileFullPath);
var data = new OpFileDownLoadRes()
{
FileName = opFile.FileName,
FilePath = fileFullPath,
//FileStream = File.ReadAllBytes(fileFullPath)
//FileStream = new FileStream(fileFullPath, FileMode.Open)
};
return DataResult<OpFileDownLoadRes>.Success(data);
}
}
}