Cześć. Chciałbym wyświetlić obrazek którego ścieżkę przechowuje w bazie. Mam aplikację FR Angular BE na .net corze. Jak przesłać a następnie wyświetlić obrazek którą przechowuję w bazie sciężkę:
Controller wygląda tak:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Route("[controller]")]
[ApiController]
public class TenureController : ControllerBase
{
private readonly ApplicationDbContext dbContext;
private readonly IHostingEnvironment host;
private readonly string[] ACCEPTED_FILE_TYPES = new[] { ".jpg", ".jpeg", ".png" };
public TenureController(ApplicationDbContext dbContext, IHostingEnvironment host)
{
this.dbContext = dbContext;
this.host = host;
}
[HttpGet]
[Route("GetAll")]
public IActionResult GetAll()
{
return Ok(dbContext.Tenures.ToList());
}
[HttpGet]
[Route("{id}/Get")]
public IActionResult Get(int id)
{
return Ok(dbContext.Tenures.SingleOrDefault(x=>x.Id == id));
}
[HttpPost]
[Route("Create")]
public IActionResult Create([FromForm]TenureEdit tenureEdit)
{
string logoUrlString = UploadImage(tenureEdit.ImageUrl);
var tenure = new Tenure
{
Name = tenureEdit.Name,
Rate = tenureEdit.Rate,
ImageUrl = logoUrlString
};
dbContext.Tenures.Add(tenure);
dbContext.SaveChanges();
return Ok();
}
[HttpPut]
[Route("{id}/Edit")]
public IActionResult Edit(int id, [FromBody]TenureEdit tenureEdit)
{
var tenure = dbContext.Tenures.SingleOrDefault(x => x.Id == id);
if (tenure == null)
{
return BadRequest();
}
tenure.Name = tenureEdit.Name;
tenure.Rate = tenureEdit.Rate;
dbContext.Entry(tenure).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
dbContext.SaveChanges();
return Ok();
}
public string UploadImage(IFormFile file)
{
if (file == null) throw new Exception("Pusty plik");
if (file.Length == 0)
{
throw new Exception("Pusty plik");
}
if (!ACCEPTED_FILE_TYPES.Any(s => s == Path.GetExtension(file.FileName).ToLower())) throw new Exception("Zły typ pliku");
if (string.IsNullOrWhiteSpace(host.WebRootPath))
{
host.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
var uploadFilesPath = Path.Combine(host.WebRootPath, "images");
if (!Directory.Exists(uploadFilesPath))
Directory.CreateDirectory(uploadFilesPath);
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadFilesPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
file.CopyToAsync(stream);
}
var path = Path.Combine(Directory.GetCurrentDirectory(), @"/wwwroot/images/", fileName);
return path;
}
}
}
a obrazki fizycznie przechowuje tutaj :
https://zapodaj.net/a8829a7a3a90b.png.html