Image 上传下载Api

1.配置

  "UploadConfig": {
// 自定义存放位置,无需放到站点内部
"Path": "C:\\Users\\kxy\\Desktop\\images\\Upload",
// 配置id对应的子目录
"Items": [
{
"id": "CeshiImg",
"path": "CeshiImg"
}
]
}

  定义类,用来接住配置

    public class UploadConfig
{
public string Path { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public string id { get; set; }
public string path { get; set; }
}

  读取配置,需要在 Startup 的 ConfigureServices 添加

            services.AddOptions();
services.Configure<UploadConfig>(Configuration.GetSection("UploadConfig"));

2.接口

    [Route("api/[controller]")]
[ApiController]
public class UploadController : ControllerBase
{
UploadConfig configs = null;
public UploadController(IOptions<UploadConfig> option)//构造函数
{
configs = option.Value;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="id">子目录id</param>
/// <param name="files">文件</param>
/// <returns></returns>
[HttpPost("{id}")]
public async Task<IActionResult> File(string id, [FromForm]List<IFormFile> files)
{
if (!SuccessConfig(id))
return Ok(new { Msg = "配置信息不存在" });
var con = configs.Items.Find(p => p.id == id);
// 保存文件夹
var saveFolder = Path.Combine(configs.Path, con.path);
if (!Directory.Exists(saveFolder))
Directory.CreateDirectory(saveFolder);
var LPath = new List<string>();
try
{
foreach (var file in files)
{
// 相对路径
var relaPath = Path.Combine(con.path, RanFileNo(id) + "." + GetFileSuf(file.FileName));
using (var stream = new FileStream(Path.Combine(configs.Path, relaPath), FileMode.Create))
{
await file.CopyToAsync(stream);
}
LPath.Add(relaPath);
}
}
catch (Exception ex)
{
throw ex;
}
return Ok(new { count = files.Count, LPath });
} /// <summary>
/// 获取文件流
/// </summary>
/// <param name="relaPath">相对路径</param>
/// <returns></returns>
[HttpGet("Get")]
public async Task<IActionResult> Get([FromQuery]string relaPath)
{
var image = System.IO.File.OpenRead(Path.Combine(configs.Path,relaPath));
return File(image, "image/jpeg");
} /// <summary>
/// 检查配置
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private bool SuccessConfig(string id)
{
if (configs == null || configs.Path == "" || configs.Path == null || configs.Items == null)
return false;
var con = configs.Items.Find(p => p.id == id);
if (con == null || con.path == "" || con.path == "")
return false;
return true;
} /// <summary>
/// 获取随机路径
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private string RanFileNo(string id)
{
return id + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + (new Random(Guid.NewGuid().GetHashCode())).Next(, ).ToString();
} /// <summary>
/// 获取文件后缀
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
private string GetFileSuf(string filename)
{
var le = filename.Split('.').Length;
if (le == )
throw new Exception("获取文件名后缀失败");
return filename.Split('.')[le - ];
}
}

3.Postman 调用接口

  1)上传

Image 上传下载Api

  2)获取

Image 上传下载Api

上一篇:Mybatis-XML 与 接口


下一篇:HTML5 & how to download SVG in js