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.

108 lines
3.9 KiB
C#

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
{
/// <summary>
/// 附件
/// </summary>
public class AnnexController : BaseApiController
{
private readonly IAnnexService annexService;
private readonly IOrderAnnexService orderAnnexService;
public AnnexController(IAnnexService annexService, IOrderAnnexService orderAnnexService)
{
this.annexService = annexService;
this.orderAnnexService = orderAnnexService;
}
///// <param name="orderId">可选;文件类型为反馈附件时的订单主键</param>
///// <param name="appendRemark">可选;文件类型为反馈附件时追加的备注信息</param>
/// <summary>
/// 附件上传接口
/// </summary>
/// <param name="file">附件文件</param>
/// <param name="fileType">文件类型</param>
[HttpPost]
public async Task<MessageModel<long>> Upload([FromForm] IFormFile file,
[FromForm] FileTypeEnum fileType)
{
if (file == null)
{
return Failed<long>("附件不能为空");
}
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);
}
/// <summary>
/// 文件下载接口
/// </summary>
[HttpGet]
public async Task<IActionResult> DownloadFile(long annexId)
{
// 如果当前登陆人非本公司,判断要下载的文件所属订单是否属于登陆人所在公司
if (!App.User.CompanyName.Contains("东胜伟业") && !App.User.CompanyName.Contains("大简云"))
{
var compId = await orderAnnexService.AsQueryable()
.InnerJoin<Order>((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);
}
}
}