ASP.Net Upload, Paste and Save Image to Database (Binary)
1. Image name = "SketchSrc1"
2. Add a HiddenField to store image string ("hf...")
<asp:HiddenField ID="hfSketchSrc1" runat="server" Value="" />
3. Add an Image component ("img...")
<asp:Image ID="imgSketchSrc1" runat="server" CssClass="img-thumbnail" ImageUrl="~/Images/NoImage.png" Width="260px" Height="260px" Style="max-width: 300px; min-height: 100px; max-height: 600px" />
4. Add "Upload", "Clear" and "Paste" button for new image ("file...", "clear...")
<div id="divImgEd1" runat="server" visible="true">
<input type="file" accept=".jpg, .jpeg" name="image1" id="fileSketchSrc1"
onchange="loadFile('SketchSrc1', event)" style="display: none;">
<label for="fileSketchSrc1" style="cursor: pointer;"
<button type="button" class="btn btn-light btn-sm"
<button id="btnPasteSketchSrc1" type="button" class="btn btn-primary btn-sm"
onclick="parseClipboardData('SketchSrc1');">Paste Image</button>
</div>
</div>
5. Add Script to bottom of aspx
<!--- --------------------------------------------------------------------- --->
<script>
var loadFile = function (mSketchSrc, event) {
//img url = blob:https://
var blobUrl = URL.createObjectURL(event.target.files[0]);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function () {
var recoveredBlob = xhr.response;
var reader = new FileReader;
//Convert blob url to Database Format
reader.onload = function () {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
document.getElementById("MainContent_hf" + mSketchSrc).value = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
}
xhr.open('GET', blobUrl);
xhr.send();
//Load Image
var image1 = document.getElementById("MainContent_img" + mSketchSrc);
image1.src = URL.createObjectURL(event.target.files[0]);
};
var clearImageSketch = function (mSketchSrc) {
var image1 = document.getElementById("MainContent_img" + mSketchSrc);
image1.src = "../Images/ImageNotAvailable.jpg";
document.getElementById("MainContent_hf" + mSketchSrc).value = image1.src;
}
//----------------------------------------
async function parseClipboardData(id) {
const items = await navigator.clipboard.read().catch((err) => {
console.error(err);
});
console.log("items:", items);
for (let item of items) {
console.log("item.type", item.types);
for (let type of item.types) {
const result = handleImage(type, item, id) || handleText(type, item, id);
if (result) {
break;
}
}
}
}
function blobToBase64(blob, callback) {
const reader = new FileReader();
reader.onloadend = function () {
//console.log("res=" + reader.result);
callback(reader.result);
};
reader.readAsDataURL(blob);
}
// parse image file
function handleImage(type, clipboardItem, id) {
//console.log(id);
if (type.startsWith("image/")) {
clipboardItem.getType(type).then((imageBlob) => {
let imageSrc = blobToBase64(imageBlob, function (base64String) {
console.log("Base64 representation of the Blob:", base64String);
document.getElementById("MainContent_img" + id).src = base64String;
document.getElementById("MainContent_hf" + id).value = base64String;
});
});
return true;
}
return false;
}
function handleText(type, clipboardItem, id) {
if (type === "text/plain") {
clipboardItem
.getType(type)
.then((blob) => blob.text())
.then((text) => {
const p = `<p>${text}</p>`;
console.log("ID=" + id);
document.getElementById("div" + id).innerHTML = p;
});
return true;
}
return false;
}
//----------------------------------------
</script>
6. Save to database (Code Behind)
string msMsgErr = "";
if (hfSketchSrc1.Value != "") //Image Found
{
string msSketch = hfSketchSrc1.Value;
byte[] imageBytes1 = null;
if (msSketch.StartsWith("data:image/png;")) //PNG file
{
//convert to JPG
msSketch = prv_Function.FromBase64PNGToBase64JPG(msSketch);
}
if ((msSketch != "") && (!msSketch.Contains("Images/ImageNotAvailable.jpg")))
{
msSketch = msSketch.Replace("data:image/jpeg;base64,", "").Replace("data:image/jpg;base64,", "");
imageBytes1 = Convert.FromBase64String(msSketch); //Convert to bytes
}
recMaFAItem mRecMaFAItem = prvMaFAItem.GetrecMaFAItem(HiddenFieldGUID.Value);
if (mRecMaFAItem.DBID != null)
{
//use provider to save image
msMsgErr = prvMaFAItem.UpdateMaFAItemPhoto(mRecMaFAItem.GUID, mRecMaFAItem.Description1, imageBytes1);
//or use SQL parameter to save. choose either one
if (msSketch != "")
{
mFBCmd.Parameters.Add("@SKETCH", SqlDbType.Binary).Value = imageBytes1;
}
//If not error, reload data
if (msMsgErr == "")
{
xpDataLoad();
}
}
}
else
{
lblImMsgPhoto.Text = "No image found";
lblImMsgPhoto.ForeColor = System.Drawing.Color.Red;
imgSketchSrc1.ImageUrl = "~/Images/NoImage.png";
}
Comments
Post a Comment