Image uploading - HSM
Image uploading - HSM
TOC:
● Technical Term: File-based uploading, File system storage, or Multipart form data
uploading.
● Description: In this method, the image file is uploaded directly to the server using a form
or AJAX request. The server typically processes the image as a file stream and saves it
to the file system (e.g., in wwwroot/images or any other designated folder).
● Characteristics: The image is stored in a binary format directly as a file on the server’s
disk or cloud storage (e.g., Azure Blob, AWS S3).
Examples:
● Form-based uploading
● AJAX-based uploading
● Drag-and-drop image uploading
● Chunked image uploading
Use Cases:
3. Use Cases:
4. Key Differences
● File system-based uploading: Works with binary file streams, directly saves files, and
is more efficient for large files. Suitable for serving files directly from the server.
● Base64 encoding: Images are sent as string data, which can increase payload size
(Base64 encoding increases the file size by approximately 33%). It’s less efficient for
large files but useful in certain scenarios where direct file streams are not practical.
6. Performance Comparison
1. Initial Load Time:
○ File System-Based: Typically faster initial load times due to smaller payloads
and potential browser caching.
○ Base64-Encoded: Larger payloads can lead to slower initial load times.
2. Subsequent Loads:
○ File System-Based: Cached images reduce load times for subsequent requests.
○ Base64-Encoded: No separate caching for images, potentially leading to slower
loads on repeat visits.
3. Database Size:
○ File System-Based: Database remains smaller as it only stores file paths or
URLs.
○ Base64-Encoded: Database size can grow significantly due to larger Base64
strings.
Example :
<script>
let baseUrl = "https://localhost:7254/api";
function uploadFile() {
var formData = new FormData();
var productName = $("#productName").val();
var productImage = $("#imageInput")[0].files[0];
if (productImage) {
formData.append("productImage", productImage);
$.ajax({
url: uploadUrl,
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (response) {
alert(response.message);
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
} else {
alert("Please select a file to upload.");
}
}
function GetImage(){
var fileName = $('#ImageName').val(); // Example file
Name
var productUrl = baseUrl +
'/ProductsApi/GetImage?fileName=' + fileName;
$.ajax({
url: productUrl,
type: 'GET',
success: function (data) {
if (data && data.imageUrl) {
var imageUrl = baseUrl +
'/ProductsApi/GetImage?fileName='+ data.productImage;
$('#productImage').attr('src',
data.imageUrl);
} else {
alert("Image not found.");
}
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
}
}
</script>
</body>
</html>
BackEnd -
Entity Framework Model:
using System.ComponentModel.DataAnnotations;
namespace YourNamespace.Models
{
public class Product
{
[Key]
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal ProductPrice { get; set; }
public string ProductImage { get; set; }
public string ImagePath { get; set; }
}
}
Controller:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
using YourNamespace.Repositories;
using System;
using System.IO;
using System.Threading.Tasks;
namespace YourNamespace.Controllers
{
public class ProductController : Controller
{
private readonly IProductRepository _productRepository;
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile productImage, string
productName, decimal productPrice)
{
if (productImage != null && productImage.Length > 0)
{
var fileName = Guid.NewGuid() +
Path.GetExtension(productImage.FileName);
var filePath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot/images", fileName);
_productRepository.AddProduct(product);
return Ok(new { message = "File uploaded successfully" });
}
return BadRequest(new { message = "No file uploaded" });
}
}
}
Repository Interface:
using YourNamespace.Models;
namespace YourNamespace.Repositories
{
public interface IProductRepository
{
void AddProduct(Product product);
}
}
Repository Implementation:
using YourNamespace.Data;
using YourNamespace.Models;
namespace YourNamespace.Repositories
{
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _context;
<script>
let baseUrl = "https://localhost:7254/api";
function uploadBase64Image() {
var file =
document.getElementById("imageInput").files[0];
var reader = new FileReader();
reader.onloadend = function () {
var base64String = reader.result.replace("data:",
"").replace(/^.+,/, "");
$.ajax({
url: baseUrl+ '/ProductsApi/UploadBase64Image',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
ProductImage: $("#productName").val(),
base64Image: base64String
}),
success: function (response) {
alert(response.message);
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
};
reader.readAsDataURL(file);
}
function GetBase64Image(){
var productId = 1; // Example product ID
var base64Url = baseUrl +
'/ProductsApi/GetBase64Image?id=' + productId;
$.ajax({
url: base64Url,
type: 'GET',
success: function (data) {
if (data && data.base64Image) {
$('#productImage').attr('src',
data.base64Image);
} else {
alert("Image not found.");
}
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
</script>
</body>
</html>
Backend (ASP.NET Core MVC Controller and Repository)
Controller:
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
using YourNamespace.Repositories;
using System;
using System.IO;
namespace YourNamespace.Controllers
{
public class ProductController : Controller
{
private readonly IProductRepository _productRepository;
[HttpPost]
public IActionResult UploadBase64Image([FromBody] Base64ImageModel model)
{
if (model == null || string.IsNullOrEmpty(model.Base64Image))
{
return BadRequest(new { message = "Invalid image data." });
}
try
{
var imageBytes = Convert.FromBase64String(model.Base64Image);
var fileName = Guid.NewGuid() + ".jpg";
var filePath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot/images", fileName);
System.IO.File.WriteAllBytes(filePath, imageBytes);
// Save product info to the database
var product = new Product
{
ProductName = model.ProductName,
ProductPrice = model.ProductPrice,
ProductImage = fileName,
ImagePath = filePath
};
_productRepository.AddProduct(product);
return Ok(new { message = "Image uploaded successfully." });
}
catch (Exception ex)
{
return StatusCode(500, new { message = "Error saving image", error =
ex.Message });
}
}
}
Image Retrieval :
Controller: ProductController.cs
using Microsoft.AspNetCore.Mvc;
using System.IO;
if (!System.IO.File.Exists(filePath))
{
return NotFound("File not found.");
}
return Json(product);
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Retrieve Product Image</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<img id="productImage" src="" alt="Product Image">
<script>
$(document).ready(function () {
var productId = 1; // Example product ID
var productUrl = '/Product/GetProduct?id=' + productId;
$.ajax({
url: productUrl,
type: 'GET',
success: function (data) {
if (data && data.productImage) {
var imageUrl = '/Product/GetImage?fileName=' + data.productImage;
$('#productImage').attr('src', imageUrl);
} else {
alert("Image not found.");
}
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
});
</script>
</body>
</html>
Controller: ProductController.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Retrieve Base64 Product Image</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<img id="productImage" src="" alt="Product Image">
<script>
$(document).ready(function () {
var productId = 1; // Example product ID
var base64Url = '/Product/GetBase64Image?id=' + productId;
$.ajax({
url: base64Url,
type: 'GET',
success: function (data) {
if (data && data.base64Image) {
$('#productImage').attr('src', data.base64Image);
} else {
alert("Image not found.");
}
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
});
</script>
</body>
</html>