Reputation: 61
I am creating an ecommerce website using Angular 7 and .net core webAPI 3.1. Both angular and webapi are created separately. i have saved product details(i.e there name ,price,image path etc) in database and images are saved to wwwroot\Products folder in .net project. Path of images is saved in db with product details. On angular side I want to show product list with there details and images.Now i am facing a problem how can i get list of product with there images in angular. I can get all details of products (i.e product list) with images file path, but images is not accessable because path is of server side wwwroot\Products folder which cannot be accessed from angular. So how can i get images with product
My Model to get Images Detail is as follow:
public class ProductImagesVM
{
[Key]
public Guid ProductId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public decimal Price { get; set; }
public decimal Discount { get; set; }
public decimal DiscountPerc { get; set; }
public Guid CategoryId { get; set; }
public string Material { get; set; }
public string Description { get; set; }
public int Status { get; set; }
public Guid ImageId { get; set; }
public string Path { get; set; }
public string ColorId { get; set; }
public string SizeId { get; set; }
public int Quantity { get; set; }
public int TotalAmount { get; set; }
}
This is my Controller method to retrieve List of Products
[HttpGet]
[Route("[action]")]
public IActionResult GetProductImagesVM()
{
return Ok(this.db.ProductImagesVM.ToList());
}
My sample response is
[
{
"productId": "9e9253dc-219c-43fd-8725-2b43c415afd7",
"name": "Product 1",
"code": "11",
"price": 500,
"discount": 300,
"discountPerc": 60,
"categoryId": "61a4d55c-6c42-4ad4-a467-382840122a25",
"material": "khadar",
"description": "description",
"status": 1,
"imageId": "99588638-025a-4d21-a591-56ec06e3bcd3",
"path": "Products\\24a9bedf-9d82-4683-902a-e160a87e25b9.jpg",
"colorId": "",
"sizeId": "",
"quantity": 0,
"totalAmount": 0
},
{
"productId": "4ae044d6-f177-404f-91f9-c0feab678310",
"name": "Men Shoes",
"code": "11",
"price": 999,
"discount": 70,
"discountPerc": 7,
"categoryId": "009e546f-2fe5-4ab2-b205-7ae562d82a32",
"material": "khadar",
"description": "description",
"status": 1,
"imageId": "012f0f16-4c5e-4234-a483-861f5feff0da",
"path": "Products\\d67d98b4-cd38-489d-bd2b-512729e94317.jpg",
"colorId": "",
"sizeId": "",
"quantity": 0,
"totalAmount": 0
}
]
This is how i save image to wwwroot/Products on server side
[HttpPost]
[Route("[action]")]
public IActionResult AddProducts()
{
try
{
var files = Request.Form.Files;
if (files != null && files.Count > 0)
{
var product = JsonConvert.DeserializeObject<Product>(Request.Form["product"]);
var images = new List<Images>();
var productSizeLink = JsonConvert.DeserializeObject<List<ProductSizeLink>>(Request.Form["size"]);
var productColorLink = JsonConvert.DeserializeObject<List<ProductColorLink>>(Request.Form["colors"]);
// var category = JsonConvert.DeserializeObject<Category>(Request.Form["category"]);
// var indexImg=Convert.ToInt32(Request.Form["imgIndex"]);
this.db.Product.Add(product);
foreach (var item in productSizeLink)
{
this.db.ProductSizeLink.Add(item);
}
foreach (var item in productColorLink)
{
this.db.ProductColorLink.Add(item);
}
string webRootPath = this._env.WebRootPath;
var folderName = "Products";
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
var pathtodb = "";
var i = 1;
foreach (var item in files)
{
if (item.Length > 0)
{
string fileName = item.FileName;
var gid = Guid.NewGuid().ToString();
string fullPath = Path.Combine(newPath, gid + Path.GetExtension(fileName));
pathtodb = Path.Combine(folderName, gid + Path.GetExtension(fileName));
images.Add(new Images { ImageId = Guid.NewGuid(), ProductId = product.ProductId, Path = pathtodb, OrderBy = i++ });
using (var stream = new FileStream(fullPath, FileMode.Create))
{
item.CopyTo(stream);
}
}
}
foreach (var item2 in images)
{
Console.WriteLine(item2.ImageId + " <<----------------------------");
this.db.Images.Add(item2);
}
this.db.SaveChanges();
return Ok("Product Added Successfully");
}
return Ok("No files found");
}
catch (Exception e)
{
return BadRequest(e.Message);
}
// return Ok("Done");
}
Upvotes: 5
Views: 7774
Reputation: 18189
use img like this(xxx is the port of webapi):
<img src="https://localhost:xxx/images/red.PNG">
Here is a demo(I have cors in startup):
Startup.cs(add app.UseStaticFiles();
as below,so that you can get img with url):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
//add it here
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Upvotes: 9