using Microsoft.AspNetCore.Http;
namespace Ds.Module.File.Model
{
public class DsUserFile
{
///
/// 文件名
///
public string FileName { get; set; } = "Ds_001";
///
/// 文件大小
///
public long Length { get; set; }
///
/// 文件扩展名
///
public string Extension { get; set; } = "_xxx_";
///
/// 文件类型
///
public string FileType { get; set; } = ".png";
private static readonly string[] Filters = { ".jpg", ".png", ".bmp" };
public bool IsValid => !string.IsNullOrEmpty(this.Extension) && Filters.Contains(this.Extension);
private IFormFile file;
public IFormFile File
{
get { return file; }
set
{
if (value != null)
{
this.file = value;
this.FileType = this.file.ContentType;
this.Length = this.file.Length;
this.Extension = this.file.FileName.Substring(file.FileName.LastIndexOf('.'));
if (string.IsNullOrEmpty(this.FileName))
this.FileName = this.FileName;
}
}
}
public async Task SaveAs(string destinationDir = null)
{
if (this.file == null)
throw new ArgumentNullException("没有需要保存的文件");
if (destinationDir != null)
Directory.CreateDirectory(destinationDir);
var newName = DateTime.Now.Ticks;
var newFile = Path.Combine(destinationDir ?? "", $"{newName}{this.Extension}");
using (FileStream fs = new FileStream(newFile, FileMode.CreateNew))
{
await this.file.CopyToAsync(fs);
fs.Flush();
}
return newFile;
}
}
}