常見的使用案例是以最適化表單內嵌顯示crx存放庫中的影像。
第一個步驟是在面板元件前面加上預留位置div。 在下面的程式碼中,面板元件由其CSS類別名稱photo-upload識別。 JavaScript函式是與最適化表單相關聯的使用者端資料庫的一部分。 此函式是在檔案附件元件的初始化事件中呼叫。
/**
* Add Placeholder Div
*/
function addPlaceholderDiv(){
$(".photo-upload").prepend(" <div class='preview'' style='border:1px dotted;height:225px;width:175px;text-align:center'><br><br><div class='text'>The Image will appear here</div></div><br>");
}
使用者選取影像後,隱藏欄位ImageName會填入選取的影像名稱。 然後,此影像名稱會傳遞至damURLToFile函式,該函式會呼叫createFile函式,將URL轉換為FileReader.readAsDataURL()的Blob。
/**
* DAM URL to File Object
* @return {string}
*/
function damURLToFile (imageName) {
console.log("The image selected is "+imageName);
createFile(imageName);
}
async function createFile(imageName){
let response = await fetch('/content/dam/formsanddocuments/fieldinspection/images/'+imageName);
let data = await response.blob();
console.log(data);
let metadata = {
type: 'image/jpeg'
};
let file = new File([data], "test.jpg", metadata);
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
console.log("finished reading ...."+reader.result);
};
var image = new Image();
$(".photo-upload .preview .imageP").remove();
$(".photo-upload .preview .text").remove();
image.width = 484;image.height = 334;
image.className = "imageP";
image.addEventListener("load", function () {
$(".photo-upload .preview")[0].prepend(this);
});
console.log(window.URL.createObjectURL(file));
image.src = window.URL.createObjectURL(file);
}