做网站还是租用服务器,海口网站建设过程,网站建设的技术标准,佛山企业网站制作哪家好1前言上传文件的接口设计有两种风格#xff0c;一种是整个项目只设置一个接口用来上传#xff0c;然后其他需要用到文件的地方#xff0c;都只存一个引用ID#xff1b;另一种是每个需要文件的地方单独管理各自的文件。这俩各有优劣吧#xff0c;本项目中选择的是后者的风格…1前言上传文件的接口设计有两种风格一种是整个项目只设置一个接口用来上传然后其他需要用到文件的地方都只存一个引用ID另一种是每个需要文件的地方单独管理各自的文件。这俩各有优劣吧本项目中选择的是后者的风格文章图片和照片模块又要能CRUD又要批量导入还是各自管理文件比较好。2图片接口说会正题先介绍一下图片相关接口。图片列表首先CRUD是肯定有的图片列表的分页查看也是有的不过因为筛选功能没有做所以就不定义一个ViewModel作为参数了。控制器代码 StarBlog.Web/Apis/Blog/PhotoController.cs[HttpGet]
public ApiResponsePagedPhoto GetList(int page 1, int pageSize 10) {var paged _photoService.GetPagedList(page, pageSize);return new ApiResponsePagedPhoto {Pagination paged.ToPaginationMetadata(),Data paged.ToList()};
}跟博客前台公用一套图片列表逻辑所以这部分抽出来放在service代码如下StarBlog.Web/Services/PhotoService.cspublic IPagedListPhoto GetPagedList(int page 1, int pageSize 10) {return _photoRepo.Select.OrderByDescending(a a.CreateTime).ToList().ToPagedList(page, pageSize);
}单个图片获取单个图片跟获取文章的差不多传入ID找不到就返回404找到就返回图片对象[HttpGet({id})]
public ApiResponsePhoto Get(string id) {var photo _photoService.GetById(id);return photo null? ApiResponse.NotFound($图片 {id} 不存在): new ApiResponsePhoto {Data photo};
}图片缩略图在本系列第20篇中本项目已经实现了图片显示的优化详见基于.NetCore开发博客项目 StarBlog - (20) 图片显示优化除了 ImageSharp 组件提供的图片缩略图功能外我这里还写了另一个生成缩略图的方法这个方法有俩特点直接在内存中生成返回不会写入缓存文件生成的是Progressive JPEG格式目前 ImageSharp 是不支持的可以优化前端的加载速度控制器代码[HttpGet({id}/Thumb)]
public async TaskIActionResult GetThumb(string id, [FromQuery] int width 300) {var data await _photoService.GetThumb(id, width);return new FileContentResult(data, image/jpeg);
}service代码/// summary
/// 生成Progressive JPEG缩略图 使用 MagickImage
/// /summary
/// param namewidth设置为0则不调整大小/param
public async Taskbyte[] GetThumb(string id, int width 0) {var photo await _photoRepo.Where(a a.Id id).FirstAsync();using (var image new MagickImage(GetPhotoFilePath(photo))) {image.Format MagickFormat.Pjpeg;if (width ! 0) {image.Resize(width, 0);}return image.ToByteArray();}
}这个 MagickImage 是用 C 写的在不同平台上引用不同 native 库需要在 csproj 里面写上配置这样发布的时候才会带上对应的依赖库而且似乎在 CentOS 系统上会有坑…!-- 复制 Magick 库 --
PropertyGroupMagickCopyNativeWindowstrue/MagickCopyNativeWindowsMagickCopyNativeLinuxtrue/MagickCopyNativeLinuxMagickCopyNativeMacOStrue/MagickCopyNativeMacOS
/PropertyGroup其他接口还有一些接口跟之前介绍的大同小异再重复一次也意义不大读者有需要的话可以自行查看源码。删除图片设置和取消推荐重建图片库数据更新每个图片的尺寸等数据一般情况下不需要用到批量导入本系列的第9篇已经介绍过详见基于.NetCore开发博客项目 StarBlog - (9) 图片批量导入3图片文件上传这个同时也是图片的添加接口先定义DTOpublic class PhotoCreationDto {/// summary/// 作品标题/// /summary[Required(ErrorMessage 作品标题不能为空)]public string Title { get; set; }/// summary/// 拍摄地点/// /summary[Required(ErrorMessage 拍摄地点不能为空)]public string Location { get; set; }
}控制器代码[Authorize]
[HttpPost]
public ApiResponsePhoto Add([FromForm] PhotoCreationDto dto, IFormFile file) {var photo _photoService.Add(dto, file);return !ModelState.IsValid? ApiResponse.BadRequest(ModelState): new ApiResponsePhoto(photo);
}因为上传的同时还要附带一些数据需要使用 FormData 传参所以这里使用 [FromForm] 特性标记这个 dto 参数IFormFile 类型的参数可以拿到上传上来的文件下面是service代码public Photo Add(PhotoCreationDto dto, IFormFile photoFile) {var photoId GuidUtils.GuidTo16String();var photo new Photo {Id photoId,Title dto.Title,CreateTime DateTime.Now,Location dto.Location,FilePath Path.Combine(photography, ${photoId}.jpg)};var savePath Path.Combine(_environment.WebRootPath, media, photo.FilePath);// 如果超出最大允许的大小则按比例缩小const int maxWidth 2000;const int maxHeight 2000;using (var image Image.Load(photoFile.OpenReadStream())) {if (image.Width maxWidth)image.Mutate(a a.Resize(maxWidth, 0));if (image.Height maxHeight)image.Mutate(a a.Resize(0, maxHeight));image.Save(savePath);}// 保存文件using (var fs new FileStream(savePath, FileMode.Create)) {photoFile.CopyTo(fs);}// 读取图片的尺寸等数据photo BuildPhotoData(photo);return _photoRepo.Insert(photo);
}这里对图片做了一些处理抛开这些细节其实对上传的文件最关键的只有几行保存代码using (var fs new FileStream(savePath, FileMode.Create)) {photoFile.CopyTo(fs);
}这样就完成了文件上传接口。4系列文章基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目基于.NetCore开发博客项目 StarBlog - (3) 模型设计基于.NetCore开发博客项目 StarBlog - (4) markdown博客批量导入基于.NetCore开发博客项目 StarBlog - (5) 开始搭建Web项目基于.NetCore开发博客项目 StarBlog - (6) 页面开发之博客文章列表基于.NetCore开发博客项目 StarBlog - (7) 页面开发之文章详情页面基于.NetCore开发博客项目 StarBlog - (8) 分类层级结构展示基于.NetCore开发博客项目 StarBlog - (9) 图片批量导入基于.NetCore开发博客项目 StarBlog - (10) 图片瀑布流基于.NetCore开发博客项目 StarBlog - (11) 实现访问统计基于.NetCore开发博客项目 StarBlog - (12) Razor页面动态编译基于.NetCore开发博客项目 StarBlog - (13) 加入友情链接功能基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能基于.NetCore开发博客项目 StarBlog - (15) 生成随机尺寸图片基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)基于.NetCore开发博客项目 StarBlog - (17) 自动下载文章里的外部图片基于.NetCore开发博客项目 StarBlog - (18) 实现本地Typora文章打包上传基于.NetCore开发博客项目 StarBlog - (19) Markdown渲染方案探索基于.NetCore开发博客项目 StarBlog - (20) 图片显示优化基于.NetCore开发博客项目 StarBlog - (21) 开始开发RESTFul接口基于.NetCore开发博客项目 StarBlog - (22) 开发博客文章相关接口基于.NetCore开发博客项目 StarBlog - (23) 文章列表接口分页、过滤、搜索、排序基于.NetCore开发博客项目 StarBlog - (24) 统一接口数据返回格式基于.NetCore开发博客项目 StarBlog - (25) 图片接口与文件上传