I'm creating a web API Rest service as micro-service using .Net Core Web API, to upload images to PostgreSQL Database. and I want to create a get action to return the image by ID I really dont know how so please any help will be good, at least I need some guides please.
Here is my class
namespace Upload_images_API.Models
{
public class Image
{
public int ImageId { get; set; }
public byte[] ImageData { get; set; }
}
}
and here is my controller to post the image.
public class ImageController : ControllerBase
{
private readonly ImageDbContext _context;
public ImageController(ImageDbContext context)
{
_context = context;
}
[HttpPost("api/Image/upload")]
public async Task<IActionResult> UploadImage(Image images, List<IFormFile> ImageData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (var item in ImageData)
{
if (item.Length > 0)
{
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
images.ImageData = stream.ToArray();
}
}
}
if (images.ImageData == null)
{
return BadRequest("Image should be selected.");
}
_context.Image.Add(images);
_context.SaveChanges();
int imageid = images.ImageId;
return Ok("Image ID:" + imageid);
}
please, any help would be appreciated, and thanks so much.
You can create a table with a column of bytea type. In your model you can store the data in a byte[] field.
I'm using dapper framework to read and write in the database:
public static bool savePhoto(PhotoModel input, IDbConnection connection)
{
string sql = "insert into photo(id, photo, notes) VALUES (@Id, @photo, @notes)";
int res = connection.Execute(sql,new { Id = input.Id, photo = input.photo, notes = input.notes});
if (res == 1)
{
return true;
} else
{
return false;
}
}
public static List<PhotoModel> readPhotosById(Int64 id)
{
using (IDbConnection connection = DBConnection.ConnectionFactory())
{
string sql = "select id, photo, notes from photo where id = @idPhoto";
connection.Open();
List<PhotoModel> photos = connection.Query<PhotoModel>(sql, new { idPhoto = id }).AsList<PhotoModel>();
return photos;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.