优化文件上传

This commit is contained in:
不做码农
2022-03-26 20:23:47 +08:00
parent 494ccdbb88
commit 79f57c7ea5
9 changed files with 146 additions and 98 deletions

View File

@@ -1,5 +1,6 @@
using Infrastructure;
using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Extensions;
using Infrastructure.Model;
using Microsoft.AspNetCore.Hosting;
@@ -91,19 +92,53 @@ namespace ZR.Admin.WebApi.Controllers
/// <param name="formFile"></param>
/// <param name="fileDir">存储目录</param>
/// <param name="fileName">自定义文件名</param>
/// <param name="uploadType">上传类型 1、发送邮件</param>
/// <param name="storeType">上传类型1、保存到本地 2、保存到阿里云</param>
/// <returns></returns>
[HttpPost()]
[Verify]
[ActionPermissionFilter(Permission = "common")]
public async Task<IActionResult> UploadFile([FromForm(Name = "file")] IFormFile formFile, string fileName = "", string fileDir = "uploads", int uploadType = 0)
public async Task<IActionResult> UploadFile([FromForm(Name = "file")] IFormFile formFile, string fileName = "", string fileDir = "uploads", StoreType storeType = StoreType.LOCAL)
{
if (formFile == null) throw new CustomException(ResultCode.PARAM_ERROR, "上传文件不能为空");
SysFile file = new();
string fileExt = Path.GetExtension(formFile.FileName);//文件后缀
double fileSize = Math.Round(formFile.Length / 1024.0, 2);//文件大小KB
string[] NotAllowedFileExtensions = new string[] { ".bat", ".exe", ".jar", ".js" };
int MaxContentLength = 15;
if (NotAllowedFileExtensions.Contains(fileExt))
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传失败,未经允许上传类型");
}
switch (storeType)
{
case StoreType.LOCAL:
file = await SysFileService.SaveFileToLocal(WebHostEnvironment.WebRootPath, fileName, fileDir, HttpContext.GetName(), formFile);
SysFile file = await SysFileService.SaveFileToLocal(WebHostEnvironment.WebRootPath, fileName, fileDir, HttpContext.GetName(), formFile);
break;
case StoreType.ALIYUN:
if ((fileSize / 1024) > MaxContentLength)
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + MaxContentLength + " MB");
}
file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", fileDir, HttpContext.GetName())
{
StoreType = (int)StoreType.ALIYUN,
FileType = formFile.ContentType
};
file = await SysFileService.SaveFileToAliyun(file, formFile);
if (file.Id <= 0) { return ToResponse(ApiResult.Error("阿里云连接失败")); }
break;
case StoreType.TENCENT:
break;
case StoreType.QINIU:
break;
default:
break;
}
return SUCCESS(new
{
url = uploadType == 1 ? file.FileUrl : file.AccessUrl,
url = file.AccessUrl,
fileName,
fileId = file.Id.ToString()
});
@@ -134,7 +169,7 @@ namespace ZR.Admin.WebApi.Controllers
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + MaxContentLength + " MB");
}
SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", fileDir, "", HttpContext.GetName())
SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", fileDir, HttpContext.GetName())
{
StoreType = (int)Infrastructure.Enums.StoreType.ALIYUN,
FileType = formFile.ContentType