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.8 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;
8 months ago
using System.Web;
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;
}
/// <summary>
/// 附件上传接口
/// </summary>
/// <param name="file">附件文件</param>
/// <param name="fileType">文件类型</param>
[HttpPost]
public async Task<MessageModel<long>> Upload([FromForm] IFormFile file,
8 months ago
[FromForm] FileTypeEnum fileType)
{
if (file == null)
{
return Failed<long>("附件不能为空");
}
8 months ago
//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,
8 months ago
Path = Path.Combine(@"files", newFileName),
Type = (int)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();
}
8 months ago
var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, file.Path);
if (!System.IO.File.Exists(filePath))
{
return NotFound();
}
8 months ago
// 读取filePath文件的内容并返回给客户端
var p = HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8);
return PhysicalFile(filePath, "application/octet-stream", p);
}
}
}