using EntrustSettle.Common;
using EntrustSettle.Controllers;
using EntrustSettle.IServices;
using EntrustSettle.Model;
using EntrustSettle.Model.Models;
using EntrustSettle.Model.Validator;
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
namespace EntrustSettle.Api.Controllers
{
///
/// 附件
///
public class AnnexController : BaseApiController
{
private readonly IAnnexService annexService;
private readonly IOrderAnnexService orderAnnexService;
public AnnexController(IAnnexService annexService, IOrderAnnexService orderAnnexService)
{
this.annexService = annexService;
this.orderAnnexService = orderAnnexService;
}
///// 可选;文件类型为反馈附件时的订单主键
///// 可选;文件类型为反馈附件时追加的备注信息
///
/// 附件上传接口
///
/// 附件文件
/// 文件类型
[HttpPost]
public async Task> Upload([FromForm] IFormFile file,
[FromForm] FileTypeEnum fileType)
{
if (file == null)
{
return Failed("附件不能为空");
}
new FileTypeEnumValidator().ValidateAndThrow(fileType);
// 文件目录
var dir = Path.Combine(App.WebHostEnvironment.WebRootPath, "files");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
// 文件名
var newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
// 完整路径
var fullPath = Path.Combine(dir, newFileName);
// 保存
using (var stream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
// 保存文件信息到数据库
var model = new Annex()
{
Name = file.FileName,
Path = Path.Combine(dir, newFileName),
Type = (byte)fileType
};
var annexId = await annexService.Add(model);
return Success(annexId);
}
///
/// 文件下载接口
///
[HttpGet]
public async Task DownloadFile(long annexId)
{
// 如果当前登陆人非本公司,判断要下载的文件所属订单是否属于登陆人所在公司
if (!App.User.CompanyName.Contains("东胜伟业") && !App.User.CompanyName.Contains("大简云"))
{
var compId = await orderAnnexService.AsQueryable()
.InnerJoin((an, o) => an.OrderId == o.Id)
.Where(an => an.AnnexId == annexId)
.Select((an, o) => o.CompanyId)
.FirstAsync();
if (compId != App.User.CompanyId)
{
throw new Exception("附件所属订单与登陆人不匹配");
}
}
var file = await annexService.QueryById(annexId);
if (file == null)
{
return NotFound();
}
var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "files", file.Path);
if (!System.IO.File.Exists(filePath))
{
return NotFound();
}
var stream = new FileStream(file.Path, FileMode.Open);
return File(stream, "application/octet-stream", file.Name);
}
}
}