0% found this document useful (0 votes)
3 views

Image uploading - HSM

The document discusses two methods of image uploading: File System-based and Base64 Encoded. File System-based uploading involves directly uploading images to the server, while Base64 Encoded uploading converts images to a string format for transmission. Key differences include efficiency, payload size, and database storage implications, with performance comparisons highlighting faster load times for File System-based uploads.

Uploaded by

urushajoshi521
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Image uploading - HSM

The document discusses two methods of image uploading: File System-based and Base64 Encoded. File System-based uploading involves directly uploading images to the server, while Base64 Encoded uploading converts images to a string format for transmission. Key differences include efficiency, payload size, and database storage implications, with performance comparisons highlighting faster load times for File System-based uploads.

Uploaded by

urushajoshi521
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Image uploading

TOC:

1. File System-based Image Uploading


2. Base64 Encoded Image Uploading
3. Use cases
4. Key Differences
5. Performance Comparison

1. File System-based Image Uploading

● 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:

● Storing images in a physical directory on the server.


● Serving images from a server’s file system or cloud storage.

2. Base64 Encoded Image Uploading

● Technical Term: Base64 encoding image upload.


● Description: The image is converted into a Base64 string on the client-side and sent as
part of the request (usually as JSON). On the server-side, the string is decoded back into
an image and stored in the file system or database.
● Characteristics: The image is handled as a string during transmission, often used when
images are transmitted as part of a JSON request, such as when sending metadata or
for scenarios where binary data isn't suitable for transmission (e.g., REST APIs that
prefer JSON payloads).

3. Use Cases:

● When transmitting image data alongside other JSON-encoded data.


● When the image is to be stored directly in a database as Base64 or in situations where
binary files are not allowed or suitable for transmission.

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 :

AJAX-based Image Uploading


Frontend –
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Upload Image</h2>
<form id="uploadForm">
<input type="text" id="productName" placeholder="Product
Name">
<input type="file" id="imageInput" name="productImage">
<button type="button" onclick="uploadFile()">Upload</button>
<button type="button"
onclick="uploadBase64Image()">Bas64stringUpload</button>

<input type="text" id="ImageName" placeholder="Image Name"


required>
<button type="button" onclick="GetImage()">Get
Image</button>
<button type="button" onclick="GetBase64Image()">Get Base64
Image</button>
<img id="productImage" src="" alt="Product Image">
</form>

<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);

let uploadUrl = baseUrl +


'/ProductsApi/UploadFile?productName=' + productName;

$.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;

public ProductController(IProductRepository productRepository)


{
_productRepository = 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);

using (var stream = new FileStream(filePath, FileMode.Create))


{
await productImage.CopyToAsync(stream);
}

// Save product info to the database


var product = new Product
{
ProductName = productName,
ProductPrice = productPrice,
ProductImage = fileName,
ImagePath = filePath
};

_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;

public ProductRepository(ApplicationDbContext context)


{
_context = context;
}

public void AddProduct(Product product)


{
_context.Products.Add(product);
_context.SaveChanges();
}
}
}

Base64 Encoded Image Uploading :


<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Upload Image</h2>
<form id="uploadForm">
<input type="text" id="productName" placeholder="Product
Name">
<input type="file" id="imageInput" name="productImage">
<button type="button" onclick="uploadFile()">Upload</button>
<button type="button"
onclick="uploadBase64Image()">Bas64stringUpload</button>

<input type="text" id="ImageName" placeholder="Image Name"


required>
<button type="button" onclick="GetImage()">Get
Image</button>
<button type="button" onclick="GetBase64Image()">Get Base64
Image</button>
<img id="productImage" src="" alt="Product Image">
</form>

<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;

public ProductController(IProductRepository productRepository)


{
_productRepository = 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 });
}
}
}

public class Base64ImageModel


{
public string ProductName { get; set; }
public decimal ProductPrice { get; set; }
public string Base64Image { get; set; }
}
}

Image Retrieval :

1. File System-Based Image Retrieval

Backend (ASP.NET Core MVC)

Controller: ProductController.cs

using Microsoft.AspNetCore.Mvc;
using System.IO;

public class ProductController : Controller


{
// Action to serve image files
[HttpGet]
public IActionResult GetImage(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return BadRequest("File name is not provided.");
}

var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images",


fileName);

if (!System.IO.File.Exists(filePath))
{
return NotFound("File not found.");
}

var fileBytes = System.IO.File.ReadAllBytes(filePath);


return File(fileBytes, "image/jpeg"); // Adjust MIME type based on image format
}

// Action to get product details including image file name


[HttpGet]
public IActionResult GetProduct(int id)
{
var product = _productRepository.GetProductById(id);
if (product == null)
{
return NotFound();
}

return Json(product);
}
}

Frontend (jQuery AJAX)

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>

2. Base64 String-Based Image Retrieval

Backend (ASP.NET Core MVC)

Controller: ProductController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;

public class ProductController : Controller


{
// Action to get Base64 encoded image
[HttpGet]
public IActionResult GetBase64Image(int id)
{
var product = _productRepository.GetProductById(id);
if (product == null || string.IsNullOrEmpty(product.ProductImage))
{
return NotFound("Product or image not found.");
}

var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images",


product.ProductImage);
if (!System.IO.File.Exists(filePath))
{
return NotFound("Image file not found.");
}

var fileBytes = System.IO.File.ReadAllBytes(filePath);


var base64String = Convert.ToBase64String(fileBytes);

return Json(new { base64Image = "data:image/jpeg;base64," + base64String });


}
}

Frontend (jQuery AJAX)

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>

You might also like