后端实现,前端的后面说
可以先在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);
}