Asp.Net Core 使用IBrowserFile完成图片上传

Asp.Net Core 使用IBrowserFile完成图片上传

写在开头

前几天弄自己的项目时遇到的问题,发现了asp.net core 新增的IBrowserFile接口,事实上他可以满足大多数文件的上传,此处我仅以图片作为示例。

实现

添加一个帮助类FileHelper,遵循一种规范,即将静态文件资源存放至wwwroot文件夹下

public class FileHelper
{
    private static long maxFileSize = 1024 * 512;//大小

    public static async Task<string> AddImage(IBrowserFile file,string Factory)
    {
        var type = file.ContentType.Split('/');
        var picloca = $"/{type[0]}{DateTime.Now.ToString("yyyyMMddhhmmssffff")}.{type[1]}";
        var fileloca = $"images/{Factory}/{DateTime.Now.ToString("yyyy-MM")}";
        var path = Path.Combine(Environment.CurrentDirectory, $"wwwroot/{fileloca}"
            );

        if (!Directory.Exists(path))
        {
            //创建文件夹
            try { Directory.CreateDirectory(path); } catch { }
        }
        await using FileStream fs = new($"{path}/{picloca}", FileMode.Create);
        await file.OpenReadStream(maxFileSize).CopyToAsync(fs);
        return $"{fileloca}{picloca}";//返回图片路径
    }
}

ContentType属性的值是像image/png,application/pdf这种形式。而excel文件则会变成这种application/vnd.ms-excel,

在保存的时候手动改一下即可

picloca = $"/{type[0]}{DateTime.Now.ToString("yyyyMMddhhmmssffff")}.xls";

部分对应关系:

·doc => ‘application/msword’,
·bin => ‘application/octet-stream’,
·exe => ‘application/octet-stream’,
·so => ‘application/octet-stream’,
·dll => ‘application/octet-stream’,
·pdf => ‘application/pdf’,
·ai => ‘application/postscript’,
·xls => ‘application/vnd.ms-excel’,

·xlsx=>response.setContentType(“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”);

写在最后

当我们将图片保存至wwwroot文件夹后,就可以直接通过https://<hostname>/images/....查看了

posted @ 2024-06-29 10:58  ssz0312  阅读(181)  评论(0)    收藏  举报