返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
StarBlog博客开发笔记

StarBlog Blog Development Notes: Image Upload Feature

Backend implementation, frontend will be covered later You can test it in Swagger first ImageSharp component documentation: https://docs.sixlabors.com/articles/imagesharp/gettingstarted.html service private string GetPhotoFilePath(Photo photo) { return Path.Combine(_environment

曦远 (DealiAxy)约 4 分钟
目录2 个章节

Backend implementation, frontend will be covered later

You can test it in Swagger first

ImageSharp component documentation: https://docs.sixlabors.com/articles/imagesharp/gettingstarted.html

service

private string GetPhotoFilePath(Photo photo) {
    return Path.Combine(_environment.WebRootPath, "media", photo.FilePath);
}
private Photo BuildPhotoData(Photo photo) {
    var savePath = GetPhotoFilePath(photo);
    using (var img = Image.Load(savePath)) {
        photo.Height = img.Height;
        photo.Width = img.Width;
    }
    return photo;
}
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 = GetPhotoFilePath(photo);
    using (var fs = new FileStream(savePath, FileMode.Create)) {
        photoFile.CopyTo(fs);
    }
    photo = BuildPhotoData(photo);
    return _photoRepo.Insert(photo);
}

controller

[HttpPost]
public ApiResponse<Photo> Add([FromForm] string title, IFormFile file) {
    var photo = _photoService.Add(title, file);

    return !ModelState.IsValid
        ? ApiResponse.BadRequest(Response, ModelState)
        : new ApiResponse<Photo>(photo);
}

_EOF_

StarBlog Blog Development Notes: Image Upload Feature

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

StarBlog博客开发笔记(27):使用JWT保护接口

前言 这是StarBlog系列在2023年的第二篇更新😂 这几个月都在忙,更新变得很不勤快,但是拖着不更新我的心里更慌,很久没写,要开头就变得很难😑 说回正题,之前的文章里,我们已经把博客关键的接口都开发完成了,但还少了一个最关键的「认证授权」,少了这东西,网站就跟筛子一样,谁都可以来添加和删除数据,乱套了~ 关于「认证授权」的知识,会比较复杂,要学习这块的话,建议分几步: 基础概念 AspN

2023-05-03 · StarBlog博客开发笔记 · 约 1 分钟

StarBlog博客开发笔记(22):开发博客文章相关接口

前言 本文介绍博客文章相关接口的开发,作为接口开发介绍的第一篇,会写得比较详细,以抛砖引玉,后面的其他接口就粗略带过了,着重于WebApi开发的周边设施。 涉及到的接口:文章CRUD、置顶文章、推荐文章等。 开始前先介绍下AspNetCore框架的基础概念,MVC模式(前后端不分离)、WebApi模式(前后端分离),都是有Controller的。 区别在前者的Controller集成自 Contr

2023-01-02 · StarBlog博客开发笔记 · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…