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

StarBlog博客开发笔记:上传图片功能

后端实现,前端的后面说 可以先在swagger里测试 ImageSharp组件文档:https://docs.sixlabors.com/articles/imagesharp/gettingstarted.html service private string GetPhotoFilePath(Photo photo) { return Path.Combine(_environment

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

后端实现,前端的后面说

可以先在swagger里测试

ImageSharp组件文档: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博客开发笔记:上传图片功能

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

相关文章

讨论

共 0 条

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

加载评论中…